Pessoal estou com algumas dúvidas, criei um novo projeto e estou estudando JPA, para isso estou fazendo alguns testes, criei as seguintes classes…
Classe cidade :
@Entity
@Table(name = "cidade")
public class cidade {
@Id @GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String nome;
private int populacao;
private int estado;
/////gets and sets///////////
public int getEstado() {
return estado;
}
public void setEstado(int estado) {
this.estado = estado;
}
}
Classe estado:
@Entity
@Table(name = "estado")
public class estado {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int idEstado;
private String uf;
private String nome;
@OneToMany
private List<cidade> cidades;
public List<cidade> getCidades() {
return cidades;
}
public void setCidades(List<cidade> cidades) {
this.cidades = cidades;
}
}
Coloquei no persistence para criar as tabelas “create”… ele criou 3 tabelas inclusive uma de relação.
Quando eu instanciar um estado eu terei todas as cidades dele carregadas em memória? numa tabela com poucos dados ate pode mas quando for muitos dados isso é irreal, queria saber como isso funciona realmente?
Primeiramente, as cidades serão sempre carregadas no estado se voc6e estiver utilizando FETCH = EAGER ou então fazer um SELECT com JOIN FETCH. No seu caso (como você não declarou um FetchType), o padrão é LAZY, ou seja, não será carregado automaticamente. Procure sobre FetchType.EAGER e FetchType.LAZY
Segundo, uma tabela de associação foi criada porque você está usando o OneToMany unidirecional. Caso você use bidirecional, não precisa de uma terceira tabela. Estude sobre isso que você irá entender.
Agora se o seu problema eh somente exibir as cidades quando seleciona o estado (um pouco dificil de conceber, porem nao impossivel) a implementacao eh diferente.
Se não conseguiu entender, não se acanhe. Pergunte.
@Entity
@Table(name = "cidade")
public class cidade {
@Id @GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Column(name="nome", nullable=false, length=30)
private String nome;
private int populacao;
@OneToOne(fetch=FetchType.LAZY)
private estado est;
vamos lah … movido pela curiosidade, fiz um relacionamento bidirecional entre duas entidades.
Normalmente eu uso mapeamento hbm, mas concordo, anotations eh mt mais facil:
@Entity @Table(name = “subject”)
public class Subject implements Serializable {
private static final long serialVersionUID = 5044590415820747308L;
/**
* @return the serialVersionUID
*/
public static long getSerialVersionUID() {
return serialVersionUID;
}
@Id @GeneratedValue
@Column(name = "id")
private long id;
@Column(name = "name")
private String name;
@OneToMany(cascade = CascadeType.ALL ,mappedBy = "subject")
private Set<Tip> tips;
public Subject() {}
/**
* @return the id
*/
public long getId() {
return id;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @return the tips
*/
public Set<Tip> getTips() {
return tips;
}
/**
* @param id the id to set
*/
public void setId(long id) {
this.id = id;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @param tips the tips to set
*/
public void setTips(Set<Tip> tips) {
this.tips = tips;
}
@Entity @Table(name = “tip”)
public class Tip implements Serializable {
private static final long serialVersionUID = 5431992956348278386L;
/**
* @return the serialVersionUID
*/
public static long getSerialVersionUID() {
return serialVersionUID;
}
@Id @GeneratedValue
@Column(name = "id")
private long id;
@Column(name = "title")
private String title;
@Column(name = "text")
private String text;
@ManyToOne
@JoinColumn(name = "subject_id", nullable = false)
private Subject subject;
public Tip() {}
/**
* @param text
* @param title
*/
public Tip(String text, String title) {
this.text = text;
this.title = title;
}
/**
* @return the id
*/
public long getId() {
return id;
}
/**
* @return the subject
*/
public Subject getSubject() {
return subject;
}
/**
* @return the text
*/
public String getText() {
return text;
}
/**
* @return the title
*/
public String getTitle() {
return title;
}
/**
* @param id the id to set
*/
public void setId(long id) {
this.id = id;
}
/**
* @param subject the subject to set
*/
public void setSubject(Subject subject) {
this.subject = subject;
}
/**
* @param text the text to set
*/
public void setText(String text) {
this.text = text;
}
/**
* @param title the title to set
*/
public void setTitle(String title) {
this.title = title;
}
}
[/code]
[code]public class Main {
public static void main(String[] args) throws Exception {
Session sess = HibernateUtil.getSession();
Transaction tx = sess.beginTransaction();
Subject subject = new Subject();
subject.setName("TESTE");
Tip tip = new Tip("asdfdsfds", "title");
tip.setSubject(subject);
Set<Tip> tips = new HashSet<Tip>();
tips.add(tip);
subject.setTips(tips);
sess.save(subject);
tx.commit();
System.out.println("Record Inserted");
sess.close();
}