Hibernate - OneToMany双向插入导致null

时间:2016-02-06 02:50:53

标签: java mysql hibernate

所以,我正在使用Hibernate 5和SpringMVC 4制作这个webapp。 出于某种原因,我无法插入具有OneToMany关系的实体。 在我先解释一下之前,我想说我尝试了许多在这里发布的解决方案和其他论坛,但对我来说都不起作用......我不知道在尝试解决问题时我是否做错了什么问题。

这是我的数据库: My Database

现在,我最近添加了电话表。在此之前,我可以添加一个配置文件对象,它会在同一个事务中级联地址和用户实体的插入。现在,通过在代码中添加电话实体,持久操作不断抛弃我

  
    

专栏' ProfileId'不能为空

  

所有课程都有各自的Setters和Getters ......但为了保持代码简短,我删除了它们。

@Entity
@Table(name = "profile")
public class Profile {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @NotEmpty
    @Size(max = 100)
    @Column(name = "FirstName", nullable = false, unique = false, length = 100)
    private String firstName;

    @NotEmpty
    @Size(max = 100)
    @Column(name = "LastName", nullable = false, unique = false, length = 100)
    private String lastName;

    @NotNull
    @DateTimeFormat(pattern = "MM/dd/yyyy")
    @Column(name = "BirthDate", nullable = false, unique = false)
    private Timestamp birthDate;

    @Valid
    @OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinColumn(name = "UserId")
    private User user;

    @Valid
    @OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinColumn(name = "AddressId")
    private Address address;

    @Valid
    @OneToMany(fetch = FetchType.EAGER, mappedBy = "profile", cascade = CascadeType.ALL)
    private List<Phone> phones;
}

_

@Entity
@Table(name = "Phone")
public class Phone {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @NotEmpty
    @Size(max = 50)
    @Column(name = "PhoneNumber", nullable = false, unique = false, length = 50)
    private String phoneNumber;

    @Valid
    @ManyToOne(cascade = CascadeType.ALL, optional = false)
    @JoinColumn(name = "ProfileId", nullable = false)
    private Profile profile;
}

_

@Entity
@Table(name = "\"User\"", uniqueConstraints = { @UniqueConstraint(columnNames = "Username") })
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "Id", unique = true, nullable = false)
    private long id;

    @Column(name = "Username", nullable = false, unique = true, length = 80)
    private String username;

    @Column(name = "Password", nullable = false, length = 128)
    private String password;

    @Valid
    @OneToOne(fetch = FetchType.LAZY, mappedBy = "user", cascade = CascadeType.ALL)
    private Profile profile;
}

_

@Entity
@Table(name = "Address")
public class Address {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @Column(name = "FullAddress", nullable = false, unique = false, length = 100)
    private String fullAddress;

    @Column(name = "City", nullable = false, unique = false, length = 100)
    private String city;

    @Column(name = "PostalCode", nullable = false, unique = false, length = 100)
    private String postalCode;

    @OneToOne(fetch = FetchType.LAZY, mappedBy = "address", cascade = CascadeType.ALL)
    private Profile profile;
}

在我找到的类似案例的解决方案之间是:

  • 要更改Phone表的ProfileId列以使其允许空值,但在JoinColumn批注上保留nullable = false。结果是它实际插入了所有实体,但ProfileId也保存为null。
  • 更改了级联类型......仍然是同样的错误。
  • 有人说正在碰撞的EntityManager上下文......这不是我的情况。
  • 将JoinColumn注释属性设置为nullable为false。已经做了,仍然在代码上,也没有工作。
  • 在关系的两侧设置级联类型。也做了,仍然在代码上,并没有工作。
  • 将ManyToOne关系属性设置为false。也不行。

和我一样新。我理解的是,ProfileId正在接收null,因为由于某种原因,在插入Profile表之后,尚未在配置文件对象上设置生成的id ,导致手机插入失败。但我不知道如何解决。

如果您需要知道我如何持久保存对象......

sessionFactory.getCurrentSession().persist(profile);

sessionFactory已自动连接。 配置文件对象具有如下内容:

{"phones":[{"phoneNumber":"123456789"}],"user":{"username":"Nameeeeee@alksjd.com","password":"123123123"},"firstName":"Nameeeeee","lastName":"Nameeeeee","birthDate":"02/05/2016", "address":{"fullAddress":"laksjdlkas","city":"alksjdlkasjd","postalCode":"101010"}}

最后是完整的错误:

Hibernate: 
    insert 
    into
        Address
        (FullAddress, City, PostalCode) 
    values
        (?, ?, ?)
Hibernate: 
    select
        last_insert_id()
Hibernate: 
    insert 
    into
        `User` (
            Password, Username
        ) 
    values
        (?, ?)
Hibernate: 
    select
        last_insert_id()
Hibernate: 
    insert 
    into
        Profile
        (AddressId, BirthDate, FirstName, LastName, UserId) 
    values
        (?, ?, ?, ?, ?)
Hibernate: 
    select
        last_insert_id()
Hibernate: 
    insert 
    into
        Phone
        (PhoneNumber, ProfileId) 
    values
        (?, ?)
WARN  SqlExceptionHelper::logExceptions:127 - SQL Error: 1048, SQLState: 23000
ERROR SqlExceptionHelper::logExceptions:129 - Column 'ProfileId' cannot be null

添加请求的代码。

@Configuration
@EnableTransactionManagement
@ComponentScan(basePackages = { "com.configuration" })
@PropertySource(value = { "classpath:application.properties" })
public class HibernateConfiguration {

    final static Logger logger = Logger.getLogger(HibernateConfiguration.class);
    @Autowired
    private Environment environment;

    @Bean
    public LocalSessionFactoryBean sessionFactoryBean() {
        logger.info("Creating LocalSessionFactoryBean...");
        LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource());
        sessionFactoryBean.setPackagesToScan(new String[] { "com.model" });
        sessionFactoryBean.setHibernateProperties(hibernateProperties());
        return sessionFactoryBean;
    }

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
        dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
        dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
        dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
        return dataSource;
    }

    @Bean
    @Autowired
    public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
        HibernateTransactionManager transactionManager = new HibernateTransactionManager();
        transactionManager.setSessionFactory(sessionFactory);
        return transactionManager;
    }

    private Properties hibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
        properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
        properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
        properties.put("hibernate.temp.use_jdbc_metadata_defaults",
                environment.getRequiredProperty("hibernate.temp.use_jdbc_metadata_defaults"));
    }

1 个答案:

答案 0 :(得分:1)

您的代码中应该执行此操作

Phone phone = new Phone();
//... set phone vars
phone.setProfile(profile);

sessionFactory.getCurrentSession().persist(profile);