hibernate一对一映射

hibernate中一对一映射举个例子就是个人(User)与身份证(IdCard)的关系。

1、创建实体类User.java

package cn.itcast.a;

public class User {
	private int userId;
	private String userName;
	private IdCard idCard;
	public int getUserId() {
		return userId;
	}
	public void setUserId(int userId) {
		this.userId = userId;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public IdCard getIdCard() {
		return idCard;
	}
	public void setIdCard(IdCard idCard) {
		this.idCard = idCard;
	}
	
}
2、创建实体类IdCard.java

package cn.itcast.a;

public class IdCard {
	private int userId;
	private String cardNum;
	private String palce;
	private User user;
	public int getUserId() {
		return userId;
	}
	public void setUserId(int userId) {
		this.userId = userId;
	}
	public String getCardNum() {
		return cardNum;
	}
	public void setCardNum(String cardNum) {
		this.cardNum = cardNum;
	}
	public String getPalce() {
		return palce;
	}
	public void setPalce(String palce) {
		this.palce = palce;
	}
	public User getUser() {
		return user;
	}
	public void setUser(User user) {
		this.user = user;
	}
	
}

3、配置User.hbm.xml





	
	
		
		
		
			
			
		
		
				
		
		
	


4、配置IdCard.hbm.xml





	
	
		
		
		
			
			
				user
			
		
		
		
		
		
		
		 
	


5、配置hibernate.cfg.xml




	
		true
		
		com.mysql.jdbc.Driver
		jdbc:mysql:///employee
		root
		123456
		org.hibernate.dialect.MySQL5Dialect
		
		
		true
				
		true
		
		update
		
		
		
	

6、创建测试类App.java

package cn.itcast.a;

import static org.junit.Assert.*;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.junit.Test;

public class App {
	private static SessionFactory sf;
	static{
		sf=new Configuration().configure().buildSessionFactory();
	}
	@Test
	public void test() {
		Session session=sf.openSession();
		session.beginTransaction();
		
		User user = new User();
		user.setUserName("张三");
		
		IdCard idcard = new IdCard();
		idcard.setCardNum("420113");
		idcard.setPalce("武汉");
		
		idcard.setUser(user);
		
		session.save(user);
		session.save(idcard);
		
		session.getTransaction().commit();
		session.close();
	}

}

7、项目结构图为
hibernate一对一映射_第1张图片

你可能感兴趣的:(hibernate)