博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【hibernate/JPA】注解方式实现 复合主键【spring boot】
阅读量:6208 次
发布时间:2019-06-21

本文共 17415 字,大约阅读时间需要 58 分钟。

1》hibernate/JPA实现复合主键的思路:是将所有的主键属性封装在一个主键类中,提供给需要复合主键的实体类使用。

2》主键类的几点要求:

1. 使用复合主键的实体类必须实现Serializable接口。必须实现Serializable接口的原因很简单,我们查找数据的时候是根据主键查找的。打开Hibernate的帮助文档我们可以找到get与load方法的声明形式如下:Object load(Class theClass,Serializable id)Object get(Class theClass,Serializable id)当我们查找复合主键类的对象时,需要传递主键值给get()或load()方法的id参数,而id参数只能接收一个实现了Serializable接口的对象。而复合主键类的主键不是一个属性可以表示的,所以只能先new出复合主键类的实例(例如:new People()),然后使用主键属性的set方法将主键值赋值给主键属性,然后将整个对象传递给get()或load()方法的id参数,实现主键值的传递,所以复合主键的实体类必须实现Serializable接口。2. 使用复合主键的实体类必须重写equals和hashCode方法。必须重写equals和hashCode方法也很好理解。这两个方法使用于判断两个对象(两条记录)是否相等的。为什么要判断两个对象是否相等呢?因为数据库中的任意两条记录中的主键值是不能相同的,所以我们在程序中只要确保了两个对象的主键值不同就可以防止主键约束违例的错误出现。也许这里你会奇怪为什么不使用复合主键的实体类不重写这两个方法也没有主键违例的情况出现,这是因为使用单一主键方式,主键值是Hibernate来维护的,它会确保主键不会重复,而复合主键方式,主键值是编程人员自己维护的,所以必须重写equals和hashCode方法用于判断两个对象的主键是否相同。3. 重写的equals和hashCode方法,只与主键属性有关,普通属性不要影响这两个方法进行判断。这个原因很简单,主键才能决定一条记录,其他属性不能决定一条记录。4.主键类必须有默认的public无参数的构造方法。

 

3》hibernate/JPA注解方式实现复合主键的方式有三种

1、@Embeddable + @Id + @Embedded(@Embeddable 表示这个类可以嵌入到别的类中去,常以表示其他类的某个属性。@Embedded 它和 @Embeddable 正好相反,它用来表示某个属性是被嵌入进来的。) 2、@Embeddable + @EmbeddedId(@EmbeddedId = @Embedded + @Id) 3、@IdClass + @Id

 

==========================================第一种注解方式实现复合主键:@Embeddable + @Id + @Embedded====================================================

1》写一个主键类ModelKey【这个主键类有点BUG,想要正确的例子,直接看下面】

package com.sxd.swapping.domain;import lombok.AllArgsConstructor;import lombok.Getter;import lombok.NoArgsConstructor;import lombok.Setter;import javax.persistence.Column;import javax.persistence.Embeddable;import java.io.Serializable;import java.util.Objects;/** * 本类 作为 复合主键类 供某个需要复合主键的类使用 * 必须提供 * 1》get/set方法 * 2》无参/全参构造 * 3》重写equals()、hashCode()方法 * 4》实现Serializable接口 * * 这里重写的equals()和hashCode()可以在idea中 alt+insert快捷键选择模板进行重写 */@Embeddable@Getter@Setter@NoArgsConstructor@AllArgsConstructorpublic class ModelKey implements Serializable{    private static final long serialVersionUID = -2397232644712659217L;    private String key1;    private String key2;    private String key3;    @Override    public boolean equals(Object o) {        if (this == o) return true;        if (o == null || getClass() != o.getClass()) return false;        ModelKey modelKey = (ModelKey) o;        return Objects.equals(key1, modelKey.key1) &&                Objects.equals(key2, modelKey.key2) &&                Objects.equals(key3, modelKey.key3);    }    @Override    public int hashCode() {        return Objects.hash(key1, key2, key3);    }}
View Code

2》实体类ModelEntity使用主键类作为复合主键

package com.sxd.swapping.domain;import lombok.Getter;import lombok.Setter;import javax.persistence.*;@Entity@Table(name = "model_entity")@Getter@Setterpublic class ModelEntity{    @Id    @Embedded    private ModelKey modelKey;    @Column(name = "user_name")    private String userName;    @Column(name = "password")    private String password;}
View Code

 

在启动创建过程中,报错:

2018-05-14 14:23:51.949  INFO 7156 --- [  restartedMain] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL5DialectHibernate: drop table if exists hua_yang_areaHibernate: drop table if exists model_entityHibernate: create table hua_yang_area (id bigint not null auto_increment, create_date datetime not null, create_id varchar(255) not null, uid varchar(255) not null, update_date datetime, update_id varchar(255), area_name varchar(255) not null, area_person bigint not null, primary key (id)) engine=MyISAMHibernate: create table model_entity (key1 varchar(255) not null, key2 varchar(255) not null, key3 varchar(255) not null, password varchar(255), user_name varchar(255), primary key (key1, key2, key3)) engine=MyISAM2018-05-14 14:23:52.385  WARN 7156 --- [  restartedMain] o.h.t.s.i.ExceptionHandlerLoggedImpl     : GenerationTarget encountered exception accepting command : Error executing DDL via JDBC Statementorg.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL via JDBC Statement    at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67) ~[hibernate-core-5.2.16.Final.jar:5.2.16.Final]    at org.hibernate.tool.schema.internal.SchemaCreatorImpl.applySqlString(SchemaCreatorImpl.java:440) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]    at org.hibernate.tool.schema.internal.SchemaCreatorImpl.applySqlStrings(SchemaCreatorImpl.java:424) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]    at org.hibernate.tool.schema.internal.SchemaCreatorImpl.createFromMetadata(SchemaCreatorImpl.java:315) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]    at org.hibernate.tool.schema.internal.SchemaCreatorImpl.performCreation(SchemaCreatorImpl.java:166) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]    at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:135) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]    at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:121) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]    at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:155) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]    at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:72) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]    at org.hibernate.internal.SessionFactoryImpl.
(SessionFactoryImpl.java:312) [hibernate-core-5.2.16.Final.jar:5.2.16.Final] at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:460) [hibernate-core-5.2.16.Final.jar:5.2.16.Final] at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:892) [hibernate-core-5.2.16.Final.jar:5.2.16.Final] at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:57) [spring-orm-5.0.5.RELEASE.jar:5.0.5.RELEASE] at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) [spring-orm-5.0.5.RELEASE.jar:5.0.5.RELEASE] at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:390) [spring-orm-5.0.5.RELEASE.jar:5.0.5.RELEASE] at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:377) [spring-orm-5.0.5.RELEASE.jar:5.0.5.RELEASE] at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) [spring-orm-5.0.5.RELEASE.jar:5.0.5.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1761) [spring-beans-5.0.5.RELEASE.jar:5.0.5.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1698) [spring-beans-5.0.5.RELEASE.jar:5.0.5.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:579) [spring-beans-5.0.5.RELEASE.jar:5.0.5.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:501) [spring-beans-5.0.5.RELEASE.jar:5.0.5.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317) [spring-beans-5.0.5.RELEASE.jar:5.0.5.RELEASE] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) ~[spring-beans-5.0.5.RELEASE.jar:5.0.5.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315) [spring-beans-5.0.5.RELEASE.jar:5.0.5.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) [spring-beans-5.0.5.RELEASE.jar:5.0.5.RELEASE] at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1089) ~[spring-context-5.0.5.RELEASE.jar:5.0.5.RELEASE] at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:859) ~[spring-context-5.0.5.RELEASE.jar:5.0.5.RELEASE] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) ~[spring-context-5.0.5.RELEASE.jar:5.0.5.RELEASE] at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140) ~[spring-boot-2.0.1.RELEASE.jar:2.0.1.RELEASE] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759) ~[spring-boot-2.0.1.RELEASE.jar:2.0.1.RELEASE] at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:395) ~[spring-boot-2.0.1.RELEASE.jar:2.0.1.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:327) ~[spring-boot-2.0.1.RELEASE.jar:2.0.1.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1255) ~[spring-boot-2.0.1.RELEASE.jar:2.0.1.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1243) ~[spring-boot-2.0.1.RELEASE.jar:2.0.1.RELEASE] at com.sxd.swapping.SwappingApplication.main(SwappingApplication.java:10) ~[classes/:na] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_171] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_171] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_171] at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_171] at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) ~[spring-boot-devtools-2.0.1.RELEASE.jar:2.0.1.RELEASE]Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Specified key was too long; max key length is 1000 bytes at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_171] at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_171] at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_171] at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_171] at com.mysql.jdbc.Util.handleNewInstance(Util.java:425) ~[mysql-connector-java-5.1.46.jar:5.1.46] at com.mysql.jdbc.Util.getInstance(Util.java:408) ~[mysql-connector-java-5.1.46.jar:5.1.46] at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:944) ~[mysql-connector-java-5.1.46.jar:5.1.46] at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3976) ~[mysql-connector-java-5.1.46.jar:5.1.46] at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3912) ~[mysql-connector-java-5.1.46.jar:5.1.46] at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2530) ~[mysql-connector-java-5.1.46.jar:5.1.46] at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2683) ~[mysql-connector-java-5.1.46.jar:5.1.46] at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2482) ~[mysql-connector-java-5.1.46.jar:5.1.46] at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2440) ~[mysql-connector-java-5.1.46.jar:5.1.46] at com.mysql.jdbc.StatementImpl.executeInternal(StatementImpl.java:845) ~[mysql-connector-java-5.1.46.jar:5.1.46] at com.mysql.jdbc.StatementImpl.execute(StatementImpl.java:745) ~[mysql-connector-java-5.1.46.jar:5.1.46] at com.zaxxer.hikari.pool.ProxyStatement.execute(ProxyStatement.java:95) ~[HikariCP-2.7.8.jar:na] at com.zaxxer.hikari.pool.HikariProxyStatement.execute(HikariProxyStatement.java) ~[HikariCP-2.7.8.jar:na] at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:54) ~[hibernate-core-5.2.16.Final.jar:5.2.16.Final] ... 39 common frames omitted
View Code

所以,需要制定创建复合主键的字段长度

只需要保证复合主键的长度总和在【1000bytes/8 = 125】以内即可。

修改:【正确的主键类ModelKey】

package com.sxd.swapping.domain;import lombok.AllArgsConstructor;import lombok.Getter;import lombok.NoArgsConstructor;import lombok.Setter;import javax.persistence.Column;import javax.persistence.Embeddable;import java.io.Serializable;import java.util.Objects;/** * 本类 作为 复合主键类 供某个需要复合主键的类使用 * 必须提供 * 1》get/set方法 * 2》无参/全参构造 * 3》重写equals()、hashCode()方法 * 4》实现Serializable接口 * * 这里重写的equals()和hashCode()可以在idea中 alt+insert快捷键选择模板进行重写 */@Embeddable@Getter@Setter@NoArgsConstructor@AllArgsConstructorpublic class ModelKey implements Serializable{    private static final long serialVersionUID = -2397232644712659217L;    @Column(length = 36)    private String key1;    @Column(length = 36)    private String key2;    @Column(length = 36)    private String key3;    @Override    public boolean equals(Object o) {        if (this == o) return true;        if (o == null || getClass() != o.getClass()) return false;        ModelKey modelKey = (ModelKey) o;        return Objects.equals(key1, modelKey.key1) &&                Objects.equals(key2, modelKey.key2) &&                Objects.equals(key3, modelKey.key3);    }    @Override    public int hashCode() {        return Objects.hash(key1, key2, key3);    }}
View Code

 

再次启动,成功执行DDL语句,查看数据表,复合主键已经创建成功。

==========================================第二种注解方式实现复合主键:@Embeddable +@EmbeddedId====================================================

 1》ModelKey主键表不变

package com.sxd.swapping.domain;import lombok.AllArgsConstructor;import lombok.Getter;import lombok.NoArgsConstructor;import lombok.Setter;import javax.persistence.Column;import javax.persistence.Embeddable;import java.io.Serializable;import java.util.Objects;/** * 本类 作为 复合主键类 供某个需要复合主键的类使用 * 必须提供 * 1》get/set方法 * 2》无参/全参构造 * 3》重写equals()、hashCode()方法 * 4》实现Serializable接口 * * 这里重写的equals()和hashCode()可以在idea中 alt+insert快捷键选择模板进行重写 */@Embeddable@Getter@Setter@NoArgsConstructor@AllArgsConstructorpublic class ModelKey implements Serializable{    private static final long serialVersionUID = -2397232644712659217L;    @Column(length = 36)    private String key1;    @Column(length = 36)    private String key2;    @Column(length = 36)    private String key3;    @Override    public boolean equals(Object o) {        if (this == o) return true;        if (o == null || getClass() != o.getClass()) return false;        ModelKey modelKey = (ModelKey) o;        return Objects.equals(key1, modelKey.key1) &&                Objects.equals(key2, modelKey.key2) &&                Objects.equals(key3, modelKey.key3);    }    @Override    public int hashCode() {        return Objects.hash(key1, key2, key3);    }}
View Code

2》ModelEntity实体表中使用@EmbeddedId注解

package com.sxd.swapping.domain;import lombok.Getter;import lombok.Setter;import javax.persistence.*;@Entity@Table(name = "model_entity")@Getter@Setterpublic class ModelEntity{    @EmbeddedId    private ModelKey modelKey;    @Column(name = "user_name")    private String userName;    @Column(name = "password")    private String password;}
View Code

 

==========================================第三种注解方式实现复合主键:@IdClass + @Id====================================================

1》ModelKey主键类取消注解@Embeddable

package com.sxd.swapping.domain;import lombok.AllArgsConstructor;import lombok.Getter;import lombok.NoArgsConstructor;import lombok.Setter;import javax.persistence.Column;import java.io.Serializable;import java.util.Objects;/** * 本类 作为 复合主键类 供某个需要复合主键的类使用 * 必须提供 * 1》get/set方法 * 2》无参/全参构造 * 3》重写equals()、hashCode()方法 * 4》实现Serializable接口 * * 这里重写的equals()和hashCode()可以在idea中 alt+insert快捷键选择模板进行重写 */@Getter@Setter@NoArgsConstructor@AllArgsConstructorpublic class ModelKey implements Serializable{    private static final long serialVersionUID = -2397232644712659217L;    @Column(length = 32)    private String key1;    @Column(length = 32)    private String key2;    @Column(length = 32)    private String key3;    @Override    public boolean equals(Object o) {        if (this == o) return true;        if (o == null || getClass() != o.getClass()) return false;        ModelKey modelKey = (ModelKey) o;        return Objects.equals(key1, modelKey.key1) &&                Objects.equals(key2, modelKey.key2) &&                Objects.equals(key3, modelKey.key3);    }    @Override    public int hashCode() {        return Objects.hash(key1, key2, key3);    }}
View Code

2》ModelEntity实体类使用@IdClass(value = ModelKey.class)标明使用哪个类作为主键类和@Id分别标记主键属性

package com.sxd.swapping.domain;import lombok.Getter;import lombok.Setter;import javax.persistence.*;@IdClass(value = ModelKey.class)@Entity@Table(name = "model_entity")@Getter@Setterpublic class ModelEntity{    @Id    private String key1;    @Id    private String key2;    @Id    private String key3;    @Column(name = "user_name")    private String userName;    @Column(name = "password")    private String password;}
View Code

这里修改了主键类三个属性的长度,可以看到数据库中,已经修改成功!

 

 

===================================最后,实体类的多个字段建立唯一索引,达到复合主键的效果=================================

 当然,一般情况下不推荐使用复合主键,或者不用实现复合主键,对实体类的多个字段建立唯一索引,同样能达到想要的效果

地址:

有兴趣可以了解一下!!

 

转载于:https://www.cnblogs.com/sxdcgaq8080/p/8444288.html

你可能感兴趣的文章
将链表中m-n范围内的数进行倒序
查看>>
怎么发表博客,还不能显示在自己的博客首页上,这还不如玩单机!
查看>>
【翻译】Ext JS 4——Ajax和Rest代理处理服务器端一场和消息的方法
查看>>
OI基础系列之最大子数组问题
查看>>
Zookeeper概述、特点、数据模型
查看>>
Nginx_lua
查看>>
微信公众号自动回复加超链接最新可用实现方案
查看>>
error: stray '\343' in program 问题解决
查看>>
小强的HTML5移动开发之路(43)——JqueryMobile页眉、工具栏和标签栏导航
查看>>
为什么说任何基于比较的算法将 5 个元素排序都需要 7 次?
查看>>
redis 持久化
查看>>
几种去除数组中重复元素的方法、数组去重
查看>>
C语言递归实现二叉树(二叉链表)的三种遍历和销毁操作(实验)
查看>>
C#的特性Attribute
查看>>
Java 编程下 Eclipse 如何设置单行代码显示的最大宽度
查看>>
【BZOJ1001】[BeiJing2006]狼抓兔子
查看>>
我的程序员之路(一) 分类: 程序人生 201...
查看>>
HTTP Methods: GET v.s POST
查看>>
onmousemove和onmouseout事件的调用,和js使用双引号、单引号的时候应该注意的问题...
查看>>
COM组件的运行机制
查看>>