简体   繁体   中英

Hibernate generates one ID for two tables/entities

In my SpringBoot Project (Java 11), I have a "user" and a "product" table. One user can have multiple products, one product can only have one user/owner. So I used a @OneToMany and @ManyToOne annotations and linked the two tables with the user_id:

My problem: The id seems to not count individually for each table, but seems to count both tables together. When I save a user it gets ID = 1. When I save a product it then gets ID = 2. But of course I want the product ID to count independently from the user ID.

用户

产品

@Entity
@Table(name="user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@OneToMany(mappedBy = "user", cascade = {CascadeType.ALL})  
private List<Product> products;



@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@ManyToOne()
@JoinColumn(name = "user_id")
private User user;

I also tried generation strategiy TABLE, but that didn't seem to change anything.

2020-06-24 09:00:46.492  INFO 11636 --- [  restartedMain]     
c.e.studileih.StudileihApplication       : Starting StudileihApplication on    
2020-06-24 09:00:46.496  INFO 11636 --- [  restartedMain] 
c.e.studileih.StudileihApplication       : No active profile set, falling   
back to default profiles: default
2020-06-24 09:00:46.564  INFO 11636 --- [  restartedMain] 
.e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active!   
Set 'spring.devtools.add-properties' to 'false' to disable
2020-06-24 09:00:46.565  INFO 11636 --- [  restartedMain] 
.e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging    
consider setting the 'logging.level.web' property to 'DEBUG'
2020-06-24 09:00:47.416  INFO 11636 --- [  restartedMain] 
.s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA 
repositories in DEFAULT mode.
2020-06-24 09:00:47.503  INFO 11636 --- [  restartedMain] 
.s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository   
scanning in 76ms. Found 2 JPA repository interfaces.
2020-06-24 09:00:48.529  INFO 11636 --- [  restartedMain] 
o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s):   
8090 (http)
2020-06-24 09:00:48.542  INFO 11636 --- [  restartedMain] 
o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2020-06-24 09:00:48.542  INFO 11636 --- [  restartedMain] 
org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache  
Tomcat/9.0.34]
2020-06-24 09:00:48.651  INFO 11636 --- [  restartedMain] o.a.c.c.C.[Tomcat].
[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2020-06-24 09:00:48.651  INFO 11636 --- [  restartedMain] 
o.s.web.context.ContextLoader            : Root WebApplicationContext: 
initialization completed in 2086 ms
2020-06-24 09:00:48.835  INFO 11636 --- [  restartedMain] 
o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing 
PersistenceUnitInfo [name: default]
2020-06-24 09:00:48.880  INFO 11636 --- [  restartedMain] 
org.hibernate.Version                    : HHH000412: Hibernate ORM core 
version 5.4.15.Final
2020-06-24 09:00:49.006  INFO 11636 --- [  restartedMain] 
o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons 
Annotations {5.1.0.Final}
2020-06-24 09:00:49.109  INFO 11636 --- [  restartedMain] 
com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2020-06-24 09:00:49.176  INFO 11636 --- [  restartedMain] 
com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2020-06-24 09:00:49.194  INFO 11636 --- [  restartedMain] 
org.hibernate.dialect.Dialect            : HHH000400: Using dialect: 
org.hibernate.dialect.MariaDB53Dialect
2020-06-24 09:00:49.270  WARN 11636 --- [  restartedMain] 
org.hibernate.cfg.AnnotationBinder       : HHH000503: A class should not be 
annotated with both @Inheritance and @MappedSuperclass. @Inheritance will be 
ignored for: com.example.studileih.Entity.BaseEntity.
Hibernate: create table `product` (`id` bigint not null, `available` bit not 
null, `created_at` datetime(6), `name` varchar(255), `pic_paths` tinyblob, 
`price` double precision not null, `title` varchar(255), `type` varchar(255), 
`updated_at` datetime(6), `views` integer not null, `user_id` bigint, primary 
key (`id`)) engine=InnoDB
Hibernate: create table `hibernate_sequence` (`next_val` bigint) 
engine=InnoDB
Hibernate: insert into `hibernate_sequence` values ( 1 )
Hibernate: insert into `hibernate_sequence` values ( 1 )
Hibernate: create table `user` (`id` bigint not null, `city` varchar(255), 
`created_at` datetime(6), `dorm` varchar(255), `email` varchar(255), `name` 
varchar(255), `password` varchar(255), `profile_pic` varchar(255), `room` 
varchar(255), `updated_at` datetime(6), primary key (`id`)) engine=InnoDB
Hibernate: alter table `product` add constraint `FKlmddkhx1lun30vpyotj9427rj` 
foreign key (`user_id`) references `user` (`id`)
2020-06-24 09:00:50.034  INFO 11636 --- [  restartedMain] 
o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform 
implementation:   
[org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-06-24 09:00:50.040  INFO 11636 --- [  restartedMain] 
j.LocalContainerEntityManagerFactoryBean : Initialized JPA   
EntityManagerFactory for persistence unit 'default'
2020-06-24 09:00:50.052  INFO 11636 --- [  restartedMain] 
o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on 
port 35729


Hibernate: select `next_val` as id_val from `hibernate_sequence` for update
Hibernate: update `hibernate_sequence` set `next_val`= ? where `next_val`=?
Hibernate: select `next_val` as id_val from `hibernate_sequence` for update
Hibernate: update `hibernate_sequence` set `next_val`= ? where `next_val`=?
Hibernate: insert into `user` (`city`, `created_at`, `dorm`, `email`, `name`, 
`password`, `profile_pic`, `room`, `updated_at`, `id`) values (?, ?, ?, ?, ?, 
?, ?, ?, ?, ?)
Hibernate: insert into `product` (`available`, `created_at`, `name`, 
`pic_paths`, `price`, `title`, `type`, `updated_at`, `user_id`, `views`, 
`id`) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: select product0_.`id` as id1_0_0_, product0_.`available` as 
availabl2_0_0_, product0_.`created_at` as created_3_0_0_, product0_.`name` as 
name4_0_0_, product0_.`pic_paths` as pic_path5_0_0_, product0_.`price` as 
price6_0_0_, product0_.`title` as title7_0_0_, product0_.`type` as 
type8_0_0_, product0_.`updated_at` as updated_9_0_0_, product0_.`user_id` as 
user_id11_0_0_, product0_.`views` as views10_0_0_ from `product` product0_ 
where product0_.`id`=?
Hibernate: update `product` set `available`=?, `name`=?, `pic_paths`=?, 
`price`=?, `title`=?, `type`=?, `updated_at`=?, `user_id`=?, `views`=? where  
`id`=?


2020-06-24 09:00:50.604  WARN 11636 --- [  restartedMain] 
JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled 
by default. Therefore, database queries may be performed during view 
rendering. Explicitly configure spring.jpa.open-in-view to disable this 
warning
2020-06-24 09:00:50.760  INFO 11636 --- [  restartedMain] 
o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 
'applicationTaskExecutor'
2020-06-24 09:00:50.977  INFO 11636 --- [  restartedMain] 
o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8090 
(http) with context path ''
2020-06-24 09:00:50.981  INFO 11636 --- [  restartedMain] 
c.e.studileih.StudileihApplication       : Started StudileihApplication in   
4.886 seconds (JVM running for 5.556)

Try with code below

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_generator")
@SequenceGenerator(name="user_generator", sequenceName = "user_seq", allocationSize=50)
@Column(name = "id", updatable = false, nullable = false)

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "product_generator")
@SequenceGenerator(name="product_generator", sequenceName = "product_seq", allocationSize=50)
@Column(name = "id", updatable = false, nullable = false)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM