hibernate

Hibernate tutorial: One-to-many mapping annotation

This Hibernate tutorial section will demonstrate how to using one-to-many annotation mapping in hibernate.
We will using source code for previous post Hibernate tutorial : many-to-one mapping annotation as base for this tutorial.
Let’s get start.

1. Project import

Download source code from this link and import to eclipse IDE. We will update code from this source code.

2. Entity diagram for this tutorial

We use mysql and create two tables with relation as below image.

many-to-one
one-to-many

Table user and login_history has a relation one-to-many it mean one record in table user have many records in login_history and each record in login_history just belong to one user.

3. Model class

Update User class

@Entity(name = "users")
public class User implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = 7292222119906752946L;
	private Long id;
	private String username;
	private String password;
	private Date crtDate;
	private Set histories;

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	@Column(name = "create_date")
	public Date getCrtDate() {
		return crtDate;
	}

	public void setCrtDate(Date crtDate) {
		this.crtDate = crtDate;
	}

	@OneToMany(mappedBy = "user",cascade=CascadeType.ALL,orphanRemoval=true)
	public Set getHistories() {
		if (histories == null) {
			histories = new HashSet();
		}
		return histories;
	}

	public void setHistories(Set histories) {
		this.histories = histories;
	}

}

@OneToMany: we annotation on method get on property histories and mappedBy point to property user on class User. We set cascade property to ALL so in any action we work with user it will detech change to make change on LoginHistory if required.
orphanRemoval=true mean when we delete user record all records relate to this user on table LoginHistory will be removed.

3. Application Entry

We change App class as below

public class App {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Session session = null;
		Transaction txn = null;
		try {
			session = HibernateUtil.openSession();
			User user = new User();
			user.setCrtDate(new Date());
			user.setUsername("thinhpt");
			user.setPassword("123456");
			LoginHistory history = new LoginHistory();
			history.setIp("127.0.0.1");
			history.setStatus("success");
			history.setLoginDate(new Date());
			history.setUser(user);
			user.getHistories().add(history);
			txn = session.beginTransaction();
			session.persist(user);
			txn.commit();
		} catch (Exception ex) {
			ex.printStackTrace();
			if (txn != null) {
				txn.rollback();
				txn = null;
			}
		} finally {
			if (session != null) {
				session.close();
				session = null;
			}
			HibernateUtil.release();
		}

	}

}

4. Run application

Run this application and it will insert a record users table and one record to login_history table.

Hibernate: insert into users (create_date, password, username) values (?, ?, ?)
Hibernate: insert into login_history (ip, login_date, status, user_id) values (?, ?, ?, ?)

5. Source code

Download source code here.

One thought on “Hibernate tutorial: One-to-many mapping annotation”

Leave a Reply