我有Person,PersonManager,PersonManagerABC和Child类。
PersonManager有一个包含人员列表(OneToMany)的字段。
它的PersonManagerABC有一个Child类型的字段。
列表正确存储在数据库中,可以从中访问。 但是将它存储在DB中后,Child就消失了(测试给出了null)
我想这只是一件小事,但我找不到它。我使用Spring Boot,Hibernate 5,CrudRepositry和H2文件DB。请帮帮我。
儿童
@Entity
public class Child {
final String localDateTime = LocalDateTime.now().toString();
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long ID;
@OneToOne
private PersonManagerAbc personManagerAbc;
public String getLocalDateTime() {
return localDateTime;
}
public Long getID() {
return ID;
}
public void setID(Long ID) {
this.ID = ID;
}
public PersonManagerAbc getPersonManagerAbc() {
return personManagerAbc;
}
public void setPersonManagerAbc(PersonManagerAbc personManagerAbc) {
this.personManagerAbc = personManagerAbc;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Child son = (Child) o;
if (localDateTime != null ? !localDateTime.equals(son.localDateTime) : son.localDateTime != null) return false;
return ID.equals(son.ID);
}
@Override
public int hashCode() {
int result = localDateTime != null ? localDateTime.hashCode() : 0;
result = 31 * result + ID.hashCode();
return result;
}
@Override
public String toString() {
System.out.println("Child: " + localDateTime);
return localDateTime;
}
}
PersonManager
@Entity
public class PersonManager extends PersonManagerAbc {
@OneToMany(mappedBy = "personManager", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
List<Person> personList = new LinkedList<>();
private String time = LocalDateTime.now().toString();
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long personManager_id;
public PersonManager(String name, Child child) {
super(name, child);
}
public PersonManager() {
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public void addPerson(Person person) {
personList.add(person);
person.setPersonManager(this);
}
public void deletePerson(Person person) {
personList.remove(person);
person.setPersonManager(this);
}
public List<Person> getPersonList() {
return personList;
}
public void setPersonList(List<Person> personList) {
this.personList = personList;
}
public Long getPersonManager_id() {
return personManager_id;
}
public void setPersonManager_id(Long personManager_id) {
this.personManager_id = personManager_id;
}
@Override
public String toString() {
return "PersonManager{" +
"localDateTime='" + getTime() + '\'' +
", time='" + time + '\'' +
'}';
}
}
PersonManagerAbc
public abstract class PersonManagerAbc {
private String localDateTime = LocalDateTime.now().toString();
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long ID;
@OneToOne(cascade = CascadeType.ALL)
private Child child;
private String name;
public PersonManagerAbc(String name, Child child) {
this.child = child;
this.name = name;
}
public PersonManagerAbc() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLocalDateTime() {
return localDateTime;
}
public void setLocalDateTime(String localDateTime) {
this.localDateTime = localDateTime;
}
public Long getID() {
return ID;
}
public void setID(Long ID) {
this.ID = ID;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PersonManagerAbc that = (PersonManagerAbc) o;
return child != null ? child.equals(that.child) : that.child == null;
}
@Override
public int hashCode() {
return child != null ? child.hashCode() : 0;
}
public Child getChild() {
return child;
}
public void setChild(Child child) {
this.child = child;
}
}
HibernateApplication
@SpringBootApplication
public class HibernateApplication {
private static final Logger log = LoggerFactory.getLogger(HibernateApplication.class);
public static void main(String[] args) {
SpringApplication.run(HibernateApplication.class);
}
@Bean
public CommandLineRunner addCustomers(PersonManagerRepo personManagerRepo) {
return (args) -> {
if (personManagerRepo.count() < 1) {
PersonManager personManager = new PersonManager("PersonManager", new Child());
personManager.addPerson(new Person("Hans", personManager));
personManager.addPerson(new Person("Peter", personManager));
personManager.addPerson(new Person("Max", personManager));
personManagerRepo.save(personManager);
}
for (PersonManager personManager1 : personManagerRepo.findAll()) {
log.info("personManager1.getPersonList().size() " + personManager1.getPersonList().size());
log.info("personManager1.toString()" + personManager1.toString());
log.info("personManager1.toString()" + personManager1.getChild());
}
log.info("");
};
}
/**
* Start internal H2 server so we can query the DB from IDE
*
* @return H2 Server instance
* @throws SQLException
*/
/*
@Bean(initMethod = "start", destroyMethod = "stop")
public Server h2Server() throws SQLException {
return Server.createTcpServer("-tcp", "-tcpAllowOthers", "-tcpPort", "9092");
}
*/
}
日志
2017-06-13 20:10:59.097 INFO 5864 --- [ main] c.e.hibernate.HibernateApplication : No active profile set, falling back to default profiles: default
2017-06-13 20:10:59.123 INFO 5864 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@4516af24: startup date [Tue Jun 13 20:10:59 CEST 2017]; root of context hierarchy
2017-06-13 20:10:59.868 INFO 5864 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$2d3c1eef] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-06-13 20:11:00.082 INFO 5864 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2017-06-13 20:11:00.089 INFO 5864 --- [ main] o.apache.catalina.core.StandardService : Starting service Tomcat
2017-06-13 20:11:00.090 INFO 5864 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.14
2017-06-13 20:11:00.146 INFO 5864 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2017-06-13 20:11:00.146 INFO 5864 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1025 ms
2017-06-13 20:11:00.220 INFO 5864 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2017-06-13 20:11:00.222 INFO 5864 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-06-13 20:11:00.222 INFO 5864 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-06-13 20:11:00.222 INFO 5864 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-06-13 20:11:00.222 INFO 5864 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2017-06-13 20:11:00.436 INFO 5864 --- [ main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2017-06-13 20:11:00.442 INFO 5864 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2017-06-13 20:11:00.474 INFO 5864 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.0.12.Final}
2017-06-13 20:11:00.475 INFO 5864 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2017-06-13 20:11:00.475 INFO 5864 --- [ main] org.hibernate.cfg.Environment : HHH000021: Bytecode provider name : javassist
2017-06-13 20:11:00.496 INFO 5864 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2017-06-13 20:11:00.548 INFO 5864 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2017-06-13 20:11:00.835 INFO 5864 --- [ main] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000227: Running hbm2ddl schema export
Hibernate: drop table person if exists
Hibernate: drop table person_manager if exists
Hibernate: create table person (person_id bigint generated by default as identity, name varchar(255), person_manager_person_manager_id bigint, primary key (person_id))
Hibernate: create table person_manager (person_manager_id bigint generated by default as identity, time varchar(255), primary key (person_manager_id))
Hibernate: alter table person add constraint FK1f8x3d159vm6o4vc2yvuebj01 foreign key (person_manager_person_manager_id) references person_manager
2017-06-13 20:11:00.847 INFO 5864 --- [ main] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000230: Schema export complete
2017-06-13 20:11:00.862 INFO 5864 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2017-06-13 20:11:01.110 INFO 5864 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@4516af24: startup date [Tue Jun 13 20:10:59 CEST 2017]; root of context hierarchy
2017-06-13 20:11:01.153 INFO 5864 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-06-13 20:11:01.153 INFO 5864 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-06-13 20:11:01.169 INFO 5864 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-06-13 20:11:01.169 INFO 5864 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-06-13 20:11:01.187 INFO 5864 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-06-13 20:11:01.318 INFO 5864 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2017-06-13 20:11:01.346 INFO 5864 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-06-13 20:11:01.365 INFO 5864 --- [ main] o.h.h.i.QueryTranslatorFactoryInitiator : HHH000397: Using ASTQueryTranslatorFactory
Hibernate: select count(*) as col_0_0_ from person_manager personmana0_
Hibernate: insert into person_manager (person_manager_id, time) values (null, ?)
Hibernate: insert into person (person_id, name, person_manager_person_manager_id) values (null, ?, ?)
Hibernate: insert into person (person_id, name, person_manager_person_manager_id) values (null, ?, ?)
Hibernate: insert into person (person_id, name, person_manager_person_manager_id) values (null, ?, ?)
Hibernate: select personmana0_.person_manager_id as person_m1_1_, personmana0_.time as time2_1_ from person_manager personmana0_
Hibernate: select personlist0_.person_manager_person_manager_id as person_m3_0_0_, personlist0_.person_id as person_i1_0_0_, personlist0_.person_id as person_i1_0_1_, personlist0_.name as name2_0_1_, personlist0_.person_manager_person_manager_id as person_m3_0_1_ from person personlist0_ where personlist0_.person_manager_person_manager_id=?
2017-06-13 20:11:01.450 INFO 5864 --- [ main] c.e.hibernate.HibernateApplication : personManager1.getPersonList().size() 3
2017-06-13 20:11:01.450 INFO 5864 --- [ main] c.e.hibernate.HibernateApplication : personManager1.toString() PersonManager{localDateTime='2017-06-13T20:11:01.411', time='2017-06-13T20:11:01.411'}
2017-06-13 20:11:01.450 INFO 5864 --- [ main] c.e.hibernate.HibernateApplication : personManager1.getChild() null
2017-06-13 20:11:01.450 INFO 5864 --- [ main] c.e.hibernate.HibernateApplication :
2017-06-13 20:11:01.451 INFO 5864 --- [ main] c.e.hibernate.HibernateApplication : Started HibernateApplication in 2.499 seconds (JVM running for 2.73)
答案 0 :(得分:0)
在儿童中删除
@OneToOne 私人PersonManagerAbc personManagerAbc;
和setter / getter