I typed out the JPA code from Java Persistence with Hibernate.
Below follows the Main method, Message.java object and PostgreSQL table description.
App.java (Main method)
// First unit of work
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
Message message = new Message("Hello World");
Long msgId = (Long) session.save(message);
tx.commit();
session.close();
// Second unit of work
Session newSession = HibernateUtil.getSessionFactory().openSession();
Transaction newTransaction = newSession.beginTransaction();
List<Message> messages = newSession.createQuery("from Message m order
by m.text asc").list();
System.out.println(messages.size() + " message(s) found:" );
for(Message m : messages) {
System.out.println(m.getText());
}
newTransaction.commit();
newSession.close();
// Third unit of work
Session thirdSession = HibernateUtil.getSessionFactory().openSession();
Transaction thirdTransaction = thirdSession.beginTransaction();
//msgId holds the identifier value of the first message
message = (Message) thirdSession.get(Message.class, msgId);
message.setText("greetings Earthling");
message.setNextMessage(
new Message("take me to your leader(please)")
);
//Shutting down the application
HibernateUtil.shutdown();
Message.java
@Entity
@Table(name = "MESSAGES")
public class Message {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE,
generator = "messages_message_id_seq")
@SequenceGenerator(name = "messages_message_id_seq",
sequenceName = "messages_message_id_seq", allocationSize = 1)
@Column(name = "MESSAGE_ID")
private Long id;
@Column(name = "MESSAGE_TEXT")
private String text;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name="NEXT_MESSAGE_ID")
private Message nextMessage;
// getters and setters
PostgreSQL Table
messages=# \d messages
Table "public.messages"
Column | Type | Modifiers
-----------------+-----------------------+---------------------------------------------
message_id | integer | not null default
nextval('messages_message_id_seq'::regclass)
message_text | character varying(25) | not null
next_message_id | integer |
When I run App.main
, only the first "unit of work" data gets inserted into the database. Here's the messages
table after running the main method:
Why isn't the next_message_id
column getting filled out? And why is the second record added to the database?
messages=# select * from messages;
message_id | message_text | next_message_id
------------+--------------+-----------------
1 | Hello World |