hibernate

Hibernate tutorial: Many-to-one mapping annotation

This quick guide will demonstrate how to using many-to-one annotation mapping in hibernate.
We will using source code for previous post Hibernate tutorial : quickstart hibernate 4, mysql (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
many-to-one

Table user and login_history has a relation many-to-one 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

Create LoginHistory model class as below

@Entity(name = "login_history")
public class LoginHistory {

	private Long id;
	private User user;
	private Date loginDate;
	private String ip;
	private String status;

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

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

	@ManyToOne(cascade={CascadeType.PERSIST})
	@JoinColumn(name="user_id")
	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	@Column(name = "login_date")
	public Date getLoginDate() {
		return loginDate;
	}

	public void setLoginDate(Date loginDate) {
		this.loginDate = loginDate;
	}

	public String getIp() {
		return ip;
	}

	public void setIp(String ip) {
		this.ip = ip;
	}

	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

}

@ManyToOne: we annotation on method get on property user relate to entity User. We also want cascade User when persistence entity LoginHistory, it mean when insert record LoginHistory it will insert/update on table user if it is not exist yet or be changed.
Note: cause we mark casacade when persistence so we must use method persistence instead of save or saveOrUpdate of hibernate session to store data.
@JoinColumn: we annotation this to specific column for joining

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.setUser(user);
			history.setStatus("success");
			history.setLoginDate(new Date());
			txn = session.beginTransaction();
			session.persist(history);
			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: Many-to-one mapping annotation”

Leave a Reply