单向N-1
情景: 合租,假设你要租房子,多个人住同一个地方,对于你来说,你只需要关心我今天晚上要住到哪里,而不需要关心。某一个地址住了哪些人,(其实还是应该关心一下的)。
表结构如下
| Field | Type | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+-------+
| id | varchar(50) | NO | PRI | NULL | |
| location | varchar(100) | NO | | NULL | |
+----------+--------------+------+-----+---------+-------+
+------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+-------------+------+-----+---------+-------+
| id | varchar(50) | NO | PRI | NULL | |
| name | varchar(50) | NO | | NULL | |
| age | int(5) | YES | | NULL | |
| address_id | varchar(50) | YES | MUL | NULL | |
+------------+-------------+------+-----+---------+-------+
无链接表的单向N-1
- 在N一端的实体增加@ManyToOne 修饰的 关联实体
- 在N一端增加外键列,实体类中用@JoinColumn修饰关联实体。
@Entity
@Table(name="tb_person")
public class Person extends AbstractEntity{
// id 我在AbstractEntity中声明了
// 需要将AbstractEntity 添加@MappedSuperclass
@Column(name="name")
private String name;
@Column(name="age")
private Integer age;
//用CasecadeType=All 主要方便的是在 Person 更新,删除,添加的时候自动把address持久化
@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name="address_id")
private Address address;
//省略set.get方法
}
因为不需要从address获取person 所以 address 只需要自己本身的属性就行。
@Entity
@Table(name="tb_address")
public class Address extends AbstractEntity{
@Column(name="location")
private String addressDetail;
public String getAddressDetail() {
return addressDetail;
}
public void setAddressDetail(String addressDetail) {
this.addressDetail = addressDetail;
}
}
测试用例
@Test
@Transactional
@Rollback(value=false)
public void testEntity(){
Session session = sessionFactory.getCurrentSession();
Person p = new Person();
Address address = new Address();
address.setAddressDetail("ZheJiang");
p.setName("WhosYourdaddy");
p.setAge(89);
p.setAddress(address);
session.save(p);
}
测试结果
+--------------------+----------+
| id | location |
+--------------------+----------+
| 170413181716030431 | ZheJiang |
+--------------------+----------+
+--------------------+---------------+------+--------------------+
| id | name | age | address_id |
+--------------------+---------------+------+--------------------+
| 170413181716014566 | WhosYourdaddy | 89 | 170413181716030431 |
+--------------------+---------------+------+--------------------+
我们再来看一下sql输出,
第一条
/* get current state com.statestr.verify.entity.Address */
select address_.id, address_.location as location2_0_ from tb_address address_ where address_.id=?
HibernateLog --> 18:17:16 TRACE org.hibernate.type.descriptor.sql.BasicBinder - binding parameter [1] as [VARCHAR] - [170413181716030431]
第二条
/* insert com.statestr.verify.entity.Address*/
insert into tb_address (location, id) values (?, ?)
HibernateLog --> 18:17:16 TRACE org.hibernate.type.descriptor.sql.BasicBinder - binding parameter [1] as [VARCHAR] - [ZheJiang]
HibernateLog --> 18:17:16 TRACE org.hibernate.type.descriptor.sql.BasicBinder - binding parameter [2] as [VARCHAR] - [170413181716030431]
第三条
insert com.statestr.verify.entity.Person*/ insert into tb_person (address_id, age, name, id) values (?, ?, ?, ?)
HibernateLog --> 18:17:16 TRACE org.hibernate.type.descriptor.sql.BasicBinder - binding parameter [1] as [VARCHAR] - [170413181716030431]
HibernateLog --> 18:17:16 TRACE org.hibernate.type.descriptor.sql.BasicBinder - binding parameter [2] as [INTEGER] - [89]
HibernateLog --> 18:17:16 TRACE org.hibernate.type.descriptor.sql.BasicBinder - binding parameter [3] as [VARCHAR] - [WhosYourdaddy]
HibernateLog --> 18:17:16 TRACE org.hibernate.type.descriptor.sql.BasicBinder - binding parameter [4] as [VARCHAR] - [170413181716014566]
总共执行了3条语句。第一条是查询是否数据库已经有了identity 相等的address。如果没有那就需要insert address.
那么如果数据库已经存在该条数据库呢?
Address address = (Address)session.get(Address.class, "170413181716030431");
// 替换
Address address = new Address();
address.setAddressDetail("ZheJiang");
第一条
select address0_.id as id1_0_0_, address0_.location as location2_0_0_ from tb_address address0_ where address0_.id=?
HibernateLog --> 19:08:43 TRACE org.hibernate.type.descriptor.sql.BasicBinder - binding parameter [1] as [VARCHAR] - [170413181716030431]
第二条
/* insert com.statestr.verify.entity.Person*/
insert into tb_person (address_id, age, name, id) values (?, ?, ?, ?)
HibernateLog --> 19:08:43 TRACE org.hibernate.type.descriptor.sql.BasicBinder - binding parameter [1] as [VARCHAR] - [170413181716030431]
HibernateLog --> 19:08:43 TRACE org.hibernate.type.descriptor.sql.BasicBinder - binding parameter [2] as [INTEGER] - [89]
HibernateLog --> 19:08:43 TRACE org.hibernate.type.descriptor.sql.BasicBinder - binding parameter [3] as [VARCHAR] - [WhosYourdaddy]
HibernateLog --> 19:08:43 TRACE org.hibernate.type.descriptor.sql.BasicBinder - binding parameter [4] as [VARCHAR] - [170413190843156966]
只执行了2条语句,因为它判断addres已经在数据库里面,而且没有改变其内容。hibernate 会跟踪每个持久化状态对象的改动。(可以参阅 http://www.bbsmax.com/A/amd03O6X5g/ ,我发现在我这个4.3.11.Final,其实所有持久化对象都存储在Session的 persistenceContext,变量中。持久化对象发生改变时,他下面的确改变了,但是没有找到保存之前状态的地方。)这里它发现对象并没有被改变。那如果对象发生改变了呢?
Address address = (Address)session.get(Address.class, "170413181716030431");
address.setAddressDetail("QingDao");
// 替换
Address address = (Address)session.get(Address.class, "170413181716030431");
// 第一条 查找数据库
select address0_.id as id1_0_0_, address0_.location as location2_0_0_ from tb_address address0_ where address0_.id=?
HibernateLog --> 19:22:02 TRACE org.hibernate.type.descriptor.sql.BasicBinder - binding parameter [1] as [VARCHAR] - [170413181716030431]
// 第二条 添加person到数据库
/* insert com.statestr.verify.entity.Person*/ insert into tb_person (address_id, age, name, id) values (?, ?, ?, ?)
HibernateLog --> 19:30:50 TRACE org.hibernate.type.descriptor.sql.BasicBinder - binding parameter [1] as [VARCHAR] - [170413181716030431]
HibernateLog --> 19:30:50 TRACE org.hibernate.type.descriptor.sql.BasicBinder - binding parameter [2] as [INTEGER] - [89]
HibernateLog --> 19:30:50 TRACE org.hibernate.type.descriptor.sql.BasicBinder - binding parameter [3] as [VARCHAR] - [WhosYourdaddy]
HibernateLog --> 19:30:50 TRACE org.hibernate.type.descriptor.sql.BasicBinder - binding parameter [4] as [VARCHAR] - [170413192101018079]
//第三条 更新address,hibernate session 检测到持久类已经发生改变
update com.statestr.verify.entity.Address */ update tb_address set location=? where id=?
HibernateLog --> 19:30:50 TRACE org.hibernate.type.descriptor.sql.BasicBinder - binding parameter [1] as [VARCHAR] - [QingDao]
HibernateLog --> 19:30:50 TRACE org.hibernate.type.descriptor.sql.BasicBinder - binding parameter [2] as [VARCHAR] - [170413181716030431]
还要注意一下调用的顺序,稍微有点偏题了...
有链接表的单向N-1
绝大多数单向N-1,都是用基于外键的。但hibernate 也支持了有连接表的N-1关系。(不常用,留个印象就行)
有连接表的单向N-1就需要用到@JoinTable,他主要用来映射底层数据库中间表。主要属性有
属性 | 是否必须 | 说明 |
---|---|---|
name | 否 | (重要)中间表的表名 |
catalog | 否 | 设置中间表放入制定的catalog |
schema | 否 | 设置中间表放入制定的schema |
targetEntity | 否 | 设定关联实体的类名。一般不需要设置,hibernate自动会获取 |
indexes | 否 | 为连接表设置多个索引 |
joinColumns | 否 | (重要)接收JoinColumn,这边设置的是JoinTable表对应当前实体的外键列 |
inverseJoinColumns | 否 | (重要)接收JoinColumn,这边设置的是JoinTable表对应关联实体的外键列 |
uniqueConstraints | 否 | 增加唯一性约束 |
(安利一个好的网站 table Generate,可以生成markdow的表格)
好接下来我们来看例子:
表结构
mysql> describe tb_person_addr_map;
+------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+-------------+------+-----+---------+-------+
| person_id | varchar(50) | NO | MUL | NULL | |
| address_id | varchar(50) | NO | MUL | NULL | |
+------------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)
mysql> describe tb_person;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id | varchar(50) | NO | PRI | NULL | |
| name | varchar(50) | NO | | NULL | |
| age | int(5) | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+
3 rows in set (0.02 sec)
mysql> describe tb_address;
+----------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+--------------+------+-----+---------+-------+
| id | varchar(50) | NO | PRI | NULL | |
| location | varchar(100) | NO | | NULL | |
+----------+--------------+------+-----+---------+-------+
2 rows in set (0.00 sec)
这边只需要该Person实体
@Entity
@Table(name="tb_person")
public class Person extends AbstractEntity{
@Column(name="name")
private String name;
@Column(name="age")
private Integer age;
@ManyToOne(cascade=CascadeType.ALL)
@JoinTable(name="tb_person_addr_map",joinColumns=@JoinColumn(name="person_id",unique=true),
inverseJoinColumns=@JoinColumn(name="address_id"))
private Address address;
// 省略set、get 方法
}
因为是N-1关联,那么Person只能有一个Address,所以添加了unique=true
我们来看sql输出:
/* get current state com.statestr.verify.entity.Address */
select address_.id, address_.location as location2_0_ from tb_address address_ where address_.id=?
HibernateLog --> 16:50:50 TRACE org.hibernate.type.descriptor.sql.BasicBinder - binding parameter [1] as [VARCHAR] - [170414165050149527]
/* insert com.statestr.verify.entity.Address*/
insert into tb_address (location, id) values (?, ?)
HibernateLog --> 16:50:50 TRACE org.hibernate.type.descriptor.sql.BasicBinder - binding parameter [1] as [VARCHAR] - [ZheJiang]
HibernateLog --> 16:50:50 TRACE org.hibernate.type.descriptor.sql.BasicBinder - binding parameter [2] as [VARCHAR] - [170414165050149527]
/* insert com.statestr.verify.entity.Person*/
insert into tb_person (age, name, id) values (?, ?, ?)
HibernateLog --> 16:50:50 TRACE org.hibernate.type.descriptor.sql.BasicBinder - binding parameter [1] as [INTEGER] - [89]
HibernateLog --> 16:50:50 TRACE org.hibernate.type.descriptor.sql.BasicBinder - binding parameter [2] as [VARCHAR] - [WhosYourdaddy]
HibernateLog --> 16:50:50 TRACE org.hibernate.type.descriptor.sql.BasicBinder - binding parameter [3] as [VARCHAR] - [170414165050149349]
/* insert com.statestr.verify.entity.Person*/
insert into tb_person_addr_map (address_id, person_id) values (?, ?)
HibernateLog --> 16:50:50 TRACE org.hibernate.type.descriptor.sql.BasicBinder - binding parameter [1] as [VARCHAR] - [170414165050149527]
HibernateLog --> 16:50:50 TRACE org.hibernate.type.descriptor.sql.BasicBinder - binding parameter [2] as [VARCHAR] - [170414165050149349]
一共执行了4条语句。可以看到这边最后才插入到中间表中。