当前位置: 首页 > 知识库问答 >
问题:

Hibernate-一个域的双向插入导致空

艾成益
2023-03-14

所以,我正在使用Hibernate 5和SpringMVC 4制作这个网络应用程序。出于某种原因,我无法插入具有OneTo很多关系的实体。在我首先解释任何事情之前,我想说我尝试了这里和其他论坛上发布的许多解决方案,但都不适合我...我不知道我在尝试解决问题时是否做错了什么。

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

列“ProfileId”不能为null

所有类都有各自的setter和getter。。。但为了保持代码简短,我删除了它们。

@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列以使其允许null值,但在JoinColumn注释上保持null=false。这样做的结果是,它实际上插入了所有实体,但ProfileId也保存为null

像我这样的新人。。据我所知,ProfileId接收到null是因为出于某种原因,在插入Profile表之后,尚未在Profile对象上设置生成的id,这导致电话插入失败。但我不知道怎么解决。

如果您需要知道我是如何持久化对象的。。。

sessionFactory.getCurrentSession().persist(profile);

sessionFactory是自动连接的。profile对象具有以下特性:

{"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个答案

顾宣
2023-03-14

在代码的某个地方,您应该这样做

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

sessionFactory.getCurrentSession().persist(profile);
 类似资料:
  • 问题内容: 我正在尝试实现一个简单的DAO。我有道: 和一个实体: 这是appContext.xml: 除非我在之后调用或插入未执行。这是为什么?如果删除,则刷新时会出现“没有正在进行的事务”的错误,但是如果删除刷新,则不会插入到数据库中。 问题答案: 之所以这样工作是因为您使用标记了事务为只读。 如您所见,由于您仍然可以通过手动调用保留更改,因此它不会使您的事务实际上是只读的。但是,它在事务结束

  • 我有2个模型/注释类,产品细节和Vnf细节。我想使用JPA HIbernate将2个表与@Oneto很多关系连接起来 产品细节模型类在下面的@Oneto许多映射中: VNF详细信息如下所示,其中有@ManytoOne和JoinColumn: 当我插入数据时,数据被插入,但VnfDetails表中的产品ID为空。 它应该是具有"ID"的外键PRODUCT_DETAILS表。 无法解决此问题。

  • 我正在尝试使用一个需要双向ssl身份验证的web服务,它属于一家公司X。我在axis2中创建了一个客户端,并将其配置为支持https(将服务器证书导入信任库,设置密钥库路径..等等)。当我调用它时,我不允许读取超时异常。我应该提到的是,握手是通过的,关于证书没有例外(我已经处理过)。 我做了以下工作(单独和组合): -使用了axis2的壁垒, -调低了我计算机上的防火墙, -绕过了我公司的防火墙(

  • 我的程序不断崩溃。我觉得我的逻辑有问题。请帮忙!谢谢

  • 问题内容: 我有2个类:User和UserPicture具有1:1的关系。 UserPicture中的“ user”将被加载,而UserPicture中的“ userPicture”则不会加载-我错了吗? 编辑 必须添加,我只是创建一个UserPicture并插入它们(使用现有的userId)-也许我需要在UserPicture中级联“ user”? 问题答案: 您必须映射您的课程。