|
Maven2 with JPA Example |
|
@Column(name = "MESSAGE_TEXT")
private String text;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name =
"NEXT_MESSAGE_ID")
private Message nextMessage;
public Message() {
}
public Message(String text) {
this.text = text;
}
public Long getId() {
return id;
}
private void setId(Long id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Message getNextMessage() {
return nextMessage;
}
public void setNextMessage(Message
nextMessage) {
this.nextMessage = nextMessage;
}
}
Here "Message" class is mapped to "MESSAGES" table, "id", "text" and "nextMessage" properties - to "MESSAGE_ID", "MESSAGE_TEXT" and "NEXT_MESSAGE_ID" fields.
2. Now create a simple program (
HelloWorld.java ) that uses persistent "Message" object: |
|
HelloWorld.java
package hello;
import java.util.*;
import javax.persistence.*;
public class HelloWorld {
public static void main
(String[] args) {
// Start EntityManagerFactory
EntityManagerFactory emf =
Persistence.createEntity
ManagerFactory("helloworld");
// First unit of work
EntityManager em =
emf.createEntityManager();
EntityTransaction tx =
em.getTransaction();
tx.begin();
Message message =
new Message("Hello
World with JPA");
em.persist(message);
message = new Message("This is message
2");
em.persist(message);
message = new Message("This is message
3");
em.persist(message);
tx.commit();
em.close();
// Second unit of work
EntityManager newEm =
emf.createEntityManager();
EntityTransaction newTx =
newEm.getTransaction();
newTx.begin();
List messages =
newEm.createQuery
("select m from
Message m order by m.text
asc").getResultList();
System.out.println
( messages.size() + "
message(s) found:" );
for (Object m : messages) {
Message loadedMsg =
(Message) m;
System.out.println
(loadedMsg.getText());
}
Download Maven2JPA Source Code |
|
Sept 2007 | Java Jazz Up |36 |
|
|
|
Pages:
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30,
31,
32,
33,
34,
35,
36,
37,
38,
39,
40,
41,
42,
43,
44,
45,
46,
47,
48,
49,
50,
51,
52,
53 ,
54,
55,
56,
57,
58,
59,
60,
61,
62,
63 ,
64,
65 ,
66 ,
67 ,
68 ,
69 ,
70,
71,
72,
73,
74,
75,
76,
77,
78,
79, Download PDF |
|
|
|
|
|
|
|
|
|