hibernate mysql 外键_Hibernate关系映射(一) 基于外键的单向一对一

packagecom.lxit.demo2.test;importorg.hibernate.Session;importorg.hibernate.Transaction;importorg.junit.Test;importcom.lxit.entity.Account;importcom.lxit.entity.Address;importcom.lxit.util.HibernateUtil;public classAccountTest {

@Testpublic voidAdd(){

Transaction tx= null;

Session session=HibernateUtil.getSession();

tx=session.beginTransaction();

Address address= newAddress();

address.setName("深圳宝安");

session.save(address);

Account account= newAccount();

account.setName("zhangsan");

account.setPassword("123");

account.setAddress(address);try{

session.save(account);

tx.commit();

}catch(Exception e) {

e.printStackTrace();

tx.rollback();

}finally{

HibernateUtil.CloseSession(session);

}

}

@Testpublic voidAdd2(){

Transaction tx= null;

Session session=HibernateUtil.getSession();

tx=session.beginTransaction();

Address address= newAddress();

address.setName("深圳福田");

session.save(address);

Account account1= newAccount();

account1.setName("lisi");

account1.setPassword("123");

account1.setAddress(address);

Account account2= newAccount();

account2.setName("wangwu");

account2.setPassword("123");

account2.setAddress(address);try{//重复添加第二个用户,地址相同,则会报错

session.save(account1);

session.save(account2);

tx.commit();

}catch(Exception e) {

e.printStackTrace();

tx.rollback();

}finally{

HibernateUtil.CloseSession(session);

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值