hibernate一对一主键关联

首先创建两个实体类
在这里插入图片描述

User.java

public class User {
	private int id;
	private String username;
	private String password;
	private String cellphone;
	private Person person;


	public User(){
		
	}

	public Person getPerson() {
		return person;
	}
	public void setPerson(Person person) {
		this.person = person;
	}
	public int getId() {
		return id;
	}
	public void setId(int 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;
	}
	public String getCellphone() {
		return cellphone;
	}
	public void setCellphone(String cellphone) {
		this.cellphone = cellphone;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", username=" + username + ", password=" + password + ", cellphone=" + cellphone
				+ "]";
	}
	
}

person.java

public class Person {
	private int id;
	private String name;
	private int idnumber;
	private User user;
	
	public Person() {
		super();
		// TODO Auto-generated constructor stub
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getIdnumber() {
		return idnumber;
	}
	public void setIdnumber(int idnumber) {
		this.idnumber = idnumber;
	}
	public User getUser() {
		return user;
	}
	public void setUser(User user) {
		this.user = user;
	}
	@Override
	public String toString() {
		return "Person [id=" + id + ", name=" + name + ", idnumber=" + idnumber + "]";
	}
	
}

然后是hbm.xml的配置

user.hbm.xml

<hibernate-mapping package="com.entity">

    <!--类名为User,表名也为User-->
    <class name="User"  table="user">

        <!--主键映射,属性名为id,列名也为id-->
        <id name="id" column="id">
            <!--根据底层数据库主键自动增长-->
            <generator class="increment"/>
        </id>

        <!--非主键映射,属性和列名一一对应-->
        <property name="username" column="username"/>
        <property name="cellphone" column="cellphone"/>
        <property name="password" column="password"/>
        <one-to-one name="person" class="Person" cascade="all"></one-to-one>
    </class>
</hibernate-mapping>

person.hbm.xml

<hibernate-mapping package="com.entity">

    <class name="Person" table="person">
    
	    <id name="id" >
		    <generator class="increment" >
		        <param name="property" >user</param>
		    </generator>
		</id>
	
		<!--非主键映射,属性和列名一一对应-->
	    <property name="name" column="name"/>
	    <property name="idnumber" column="idnumber"/>
	    <one-to-one name="user" class="User" constrained="true" ></one-to-one>
    </class>
</hibernate-mapping>

这里user和person设置了一对一的双向关联

在配置xml是会经常用到inverse和cascade 这两个属性

inverse 有两个值 true ,false ;如果设置为true 则表示对象的状态变化不会同步到数据库 ;设置false就相反拉;
cascade 有五个选项 分别是: all ,delete ,none,save-update,delete-orphan ;
all : 所有情况下均进行关联操作。
none:所有情况下均不进行关联操作。这是默认值。
save-update:在执行save/update/saveOrUpdate时进行关联操作。
delete:在执行delete时进行关联操作。
delete-orphan: 当save/update/saveOrUpdate时,相当于save-update ;当删除操作时,相当于delete ;

constrained属性

constrained只能在one-to-one的映射中使用,(一般在主表的映射中,有外键的那个表)。如果constrained=true, 则表明存在外键与关联表对应,并且关联表中肯定存在对应的键与其对应, 另外该选项最关键的是影响save和delete的先后顺序。例如增加的时候,如果constainted=true,则会先增加关联表,然后增加本表。 删除的时候反之。

one-to-one的单向关联中,如果constrained=false,则会在查询时就全部取出来,用left outer join的方式。如果constrained=true,hibernate即会延迟加载sql,只把主表的查出来,等有用到关联表的再发sql取。

one-to- one的双向关联中,必须设置constrained=true,要不然会有重复数据读。

开始测试

添加数据

public static void add(){
		User user = new User();
	    user.setPassword("123");
	    user.setCellphone("122222");
	    user.setUsername("xxx");
	    Person person = new Person();
	    person.setName("Naive");
	    
	    person.setUser(user);
	    user.setPerson(person);
	    
	    //获取加载配置管理类
	    Configuration configuration = new Configuration().configure();
	    //创建Session工厂对象
        SessionFactory sessionFactory = configuration.buildSessionFactory();
      	//得到Session对象
        Session session = sessionFactory.openSession();
        //使用Hibernate操作数据库,都要开启事务,得到事务对象
        Transaction transaction = session.getTransaction();
        try {
        	 //开启事务
            transaction.begin();
            //把对象添加到数据库中
            session.save(user);
            //session.save(person);
            //提交事务
            transaction.commit();
		} catch (Exception e) {
			e.printStackTrace();
			transaction.rollback();
		}finally {
			 //关闭Session
	        session.close();
		}
	}

查询数据

public static void selectone(){
	//获取加载配置管理类
    Configuration configuration = new Configuration().configure();
    //创建Session工厂对象
    SessionFactory sessionFactory = configuration.buildSessionFactory();
  	//得到Session对象
    Session session = sessionFactory.openSession();
    try {
        //查询数据库
        User user =session.get(User.class, 1);
        System.out.println(user.toString());
        System.out.println(user.getPerson().toString());
	} catch (Exception e) {
		e.printStackTrace();
	}finally {
		 //关闭Session
        session.close();
	} 
}

查询结果

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值