如何使用Hibernate保存ManyToOne关系。

huangapple go评论67阅读模式
英文:

How to save a ManyToOne Relationship using hibernate

问题

我有以下 User 实体。

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="user_id")
    private int id;

    @Embedded
    private Person person;

    @Column(columnDefinition = "VARCHAR(255)")
    private String image;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="user_group_id")
    private UserGroup userGroup;
    
    // 省略部分 getter 和 setter 方法

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public UserGroup getUserGroup() {
        return userGroup;
    }

    public void setUserGroup(UserGroup userGroup) {
        this.userGroup = userGroup;
    }

以及以下可嵌入的 Person 实体。

    @NotNull
    @Column(name="firstname", nullable = false, columnDefinition = "VARCHAR(32)")
    private String firstName;

    @NotNull
    @Column(name="lastname", nullable = false, columnDefinition = "VARCHAR(32)")
    private String lastName;

    @NotNull
    @Column(nullable = false, columnDefinition = "VARCHAR(96)")
    private String email;

    @NotNull
    @Column(nullable = false, columnDefinition = "VARCHAR(24)")
    private String telephone;

    @NotNull
    @Column(nullable = false, columnDefinition = "VARCHAR(255)")
    private String password;

    @Column(nullable = false, columnDefinition = "TINYINT(1) DEFAULT 1")
    private boolean status;

    @Column(name = "date_added", nullable = false, updatable=false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP")
    @Temporal(value = TemporalType.TIMESTAMP)
    private Date dateAdded;

以及以下 UserGroup 实体。

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="user_group_id")
    private int id;

    @NotNull
    @Column(nullable = false, columnDefinition = "VARCHAR(20)")
    private String name;

    @NotNull
    @Column(nullable = false, columnDefinition = "TEXT")
    private String permission;

    @OneToMany(mappedBy="userGroup",
    cascade={CascadeType.PERSIST, CascadeType.MERGE},
    fetch = FetchType.LAZY)
    private List<User> users = new ArrayList<User>();
    
    // 省略部分 getter 和 setter 方法

我已经在数据库中设置了几个用户组。当添加新用户时,我检索特定组并想将其分配给新用户。我使用以下代码来实现。

        Session session = HibernateHelper.getSessionFactory().openSession();
        UserGroup userGroup = (UserGroup) session.createQuery("FROM UserGroup UG WHERE UG.id = :user_group_id")
                .setParameter("user_group_id",Integer.parseInt(group))
                .getSingleResult();

        Transaction tx = session.getTransaction();
        tx.begin();

        User user = new User();
        user.setPerson(new Person());
        user.getPerson().setFirstName(firstName);
        user.getPerson().setLastName(lastName);
        user.getPerson().setEmail(email);
        user.getPerson().setTelephone(telephone);
        user.getPerson().setPassword(hashedPassword);

        user.setUserGroup(userGroup); // 将新用户分配给该组

        session.save(user);
        tx.commit();
        session.close();

然而,我收到异常:org.hibernate.exception.ConstraintViolationException。正确的做法是什么?

我正在开发一个基于 Wildfly 服务器的 Servlets 运行的 Web 应用程序。

错误堆栈跟踪:

org.hibernate.exception.ConstraintViolationException: could not execute statement
	at deployment.shopping_cart.war//org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:59)
	...
Caused by: java.sql.SQLIntegrityConstraintViolationException: Column 'date_added' cannot be null
	at deployment.shopping_cart.war//com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:117)
	...
英文:

I have the following User entity.

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name=&quot;user_id&quot;)
    private int id;

    @Embedded
    private Person person;

    @Column(columnDefinition = &quot;VARCHAR(255)&quot;)
    private String image;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name=&quot;user_group_id&quot;)
    private UserGroup userGroup;
    
    // Some getters and setters ommitted

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public UserGroup getUserGroup() {
        return userGroup;
    }

    public void setUserGroup(UserGroup userGroup) {
        this.userGroup = userGroup;
    }

And the following embeddable Person entity.

    @NotNull
    @Column(name=&quot;firstname&quot;, nullable = false, columnDefinition = &quot;VARCHAR(32)&quot;)
    private String firstName;

    @NotNull
    @Column(name=&quot;lastname&quot;, nullable = false, columnDefinition = &quot;VARCHAR(32)&quot;)
    private String lastName;

    @NotNull
    @Column(nullable = false, columnDefinition = &quot;VARCHAR(96)&quot;)
    private String email;

    @NotNull
    @Column(nullable = false, columnDefinition = &quot;VARCHAR(24)&quot;)
    private String telephone;

    @NotNull
    @Column(nullable = false, columnDefinition = &quot;VARCHAR(255)&quot;)
    private String password;

    @Column(nullable = false, columnDefinition = &quot;TINYINT(1) DEFAULT 1&quot;)
    private boolean status;

    @Column(name = &quot;date_added&quot;, nullable = false, updatable=false, columnDefinition = &quot;DATETIME DEFAULT CURRENT_TIMESTAMP&quot;)
    @Temporal(value = TemporalType.TIMESTAMP)
    private Date dateAdded;

And the following UserGroup entity.

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name=&quot;user_group_id&quot;)
    private int id;

    @NotNull
    @Column(nullable = false, columnDefinition = &quot;VARCHAR(20)&quot;)
    private String name;

    @NotNull
    @Column(nullable = false, columnDefinition = &quot;TEXT&quot;)
    private String permission;

    @OneToMany(mappedBy=&quot;userGroup&quot;,
    cascade={CascadeType.PERSIST, CascadeType.MERGE},
    fetch = FetchType.LAZY)
    private List&lt;User&gt; users = new ArrayList&lt;User&gt;();
    
    // Getters and Setters ommitted

I already have a couple of user groups set up in the db. When adding a new user, I retrieve a specific group and want to assign it to the new user. I use the following code to do so.

        Session session = HibernateHelper.getSessionFactory().openSession();
        UserGroup userGroup = (UserGroup) session.createQuery(&quot;FROM UserGroup UG WHERE UG.id = :user_group_id&quot;)
                .setParameter(&quot;user_group_id&quot;,Integer.parseInt(group))
                .getSingleResult();

        Transaction tx = session.getTransaction();
        tx.begin();

        User user = new User();
        user.setPerson(new Person());
        user.getPerson().setFirstName(firstName);
        user.getPerson().setLastName(lastName);
        user.getPerson().setEmail(email);
        user.getPerson().setTelephone(telephone);
        user.getPerson().setPassword(hashedPassword);

        user.setUserGroup(userGroup); // Assign the new user this group

        session.save(user);
        tx.commit();
        session.close();

However I get the exception: org.hibernate.exception.ConstraintViolationException
What is the correct way to do this?

I'm developing a web app using servlets running on a wildfly server.

The error stack trace:

org.hibernate.exception.ConstraintViolationException: could not execute statement
at deployment.shopping_cart.war//org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:59)
at deployment.shopping_cart.war//org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at deployment.shopping_cart.war//org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:113)
at deployment.shopping_cart.war//org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:99)
at deployment.shopping_cart.war//org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:200)
at deployment.shopping_cart.war//org.hibernate.dialect.identity.GetGeneratedKeysDelegate.executeAndExtract(GetGeneratedKeysDelegate.java:57)
at deployment.shopping_cart.war//org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:43)
at deployment.shopping_cart.war//org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3153)
at deployment.shopping_cart.war//org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3759)
at deployment.shopping_cart.war//org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:84)
at deployment.shopping_cart.war//org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:645)
at deployment.shopping_cart.war//org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:282)
at deployment.shopping_cart.war//org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:263)
at deployment.shopping_cart.war//org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:317)
at deployment.shopping_cart.war//org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:330)
at deployment.shopping_cart.war//org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:287)
at deployment.shopping_cart.war//org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:193)
at deployment.shopping_cart.war//org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:123)
at deployment.shopping_cart.war//org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:194)
at deployment.shopping_cart.war//org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
at deployment.shopping_cart.war//org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:179)
at deployment.shopping_cart.war//org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
at deployment.shopping_cart.war//org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:75)
at deployment.shopping_cart.war//org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:102)
at deployment.shopping_cart.war//org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:634)
at deployment.shopping_cart.war//org.hibernate.internal.SessionImpl.save(SessionImpl.java:627)
at deployment.shopping_cart.war//org.hibernate.internal.SessionImpl.save(SessionImpl.java:622)
at deployment.shopping_cart.war//controllers.UserCreate.doPost(UserCreate.java:51)
at javax.servlet.api@2.0.0.Final//javax.servlet.http.HttpServlet.service(HttpServlet.java:523)
at javax.servlet.api@2.0.0.Final//javax.servlet.http.HttpServlet.service(HttpServlet.java:590)
at io.undertow.servlet@2.1.3.Final//io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:74)
at io.undertow.servlet@2.1.3.Final//io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
at io.undertow.servlet@2.1.3.Final//io.undertow.servlet.handlers.ServletChain$1.handleRequest(ServletChain.java:68)
at io.undertow.servlet@2.1.3.Final//io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
at org.wildfly.extension.undertow@20.0.1.Final//org.wildfly.extension.undertow.security.SecurityContextAssociationHandler.handleRequest(SecurityContextAssociationHandler.java:78)
at io.undertow.core@2.1.3.Final//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet@2.1.3.Final//io.undertow.servlet.handlers.RedirectDirHandler.handleRequest(RedirectDirHandler.java:68)
at io.undertow.servlet@2.1.3.Final//io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:132)
at io.undertow.servlet@2.1.3.Final//io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
at io.undertow.core@2.1.3.Final//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.core@2.1.3.Final//io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
at io.undertow.servlet@2.1.3.Final//io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
at io.undertow.core@2.1.3.Final//io.undertow.security.handlers.AuthenticationMechanismsHandler.handleRequest(AuthenticationMechanismsHandler.java:60)
at io.undertow.servlet@2.1.3.Final//io.undertow.servlet.handlers.security.CachedAuthenticatedSessionHandler.handleRequest(CachedAuthenticatedSessionHandler.java:77)
at io.undertow.core@2.1.3.Final//io.undertow.security.handlers.NotificationReceiverHandler.handleRequest(NotificationReceiverHandler.java:50)
at io.undertow.core@2.1.3.Final//io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
at io.undertow.core@2.1.3.Final//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at org.wildfly.extension.undertow@20.0.1.Final//org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
at io.undertow.core@2.1.3.Final//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at org.wildfly.extension.undertow@20.0.1.Final//org.wildfly.extension.undertow.deployment.GlobalRequestControllerHandler.handleRequest(GlobalRequestControllerHandler.java:68)
at io.undertow.core@2.1.3.Final//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet@2.1.3.Final//io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:269)
at io.undertow.servlet@2.1.3.Final//io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:78)
at io.undertow.servlet@2.1.3.Final//io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:133)
at io.undertow.servlet@2.1.3.Final//io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:130)
at io.undertow.servlet@2.1.3.Final//io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
at io.undertow.servlet@2.1.3.Final//io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
at org.wildfly.extension.undertow@20.0.1.Final//org.wildfly.extension.undertow.security.SecurityContextThreadSetupAction.lambda$create$0(SecurityContextThreadSetupAction.java:105)
at org.wildfly.extension.undertow@20.0.1.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1530)
at org.wildfly.extension.undertow@20.0.1.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1530)
at org.wildfly.extension.undertow@20.0.1.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1530)
at org.wildfly.extension.undertow@20.0.1.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1530)
at io.undertow.servlet@2.1.3.Final//io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:249)
at io.undertow.servlet@2.1.3.Final//io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:78)
at io.undertow.servlet@2.1.3.Final//io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:99)
at io.undertow.core@2.1.3.Final//io.undertow.server.Connectors.executeRootHandler(Connectors.java:370)
at io.undertow.core@2.1.3.Final//io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:830)
at org.jboss.threads@2.3.3.Final//org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
at org.jboss.threads@2.3.3.Final//org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1982)
at org.jboss.threads@2.3.3.Final//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1486)
at org.jboss.threads@2.3.3.Final//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1377)
at java.base/java.lang.Thread.run(Thread.java:832)
Caused by: java.sql.SQLIntegrityConstraintViolationException: Column &#39;date_added&#39; cannot be null
at deployment.shopping_cart.war//com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:117)
at deployment.shopping_cart.war//com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
at deployment.shopping_cart.war//com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at deployment.shopping_cart.war//com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:953)
at deployment.shopping_cart.war//com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1092)
at deployment.shopping_cart.war//com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1040)
at deployment.shopping_cart.war//com.mysql.cj.jdbc.ClientPreparedStatement.executeLargeUpdate(ClientPreparedStatement.java:1347)
at deployment.shopping_cart.war//com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdate(ClientPreparedStatement.java:1025)
at deployment.shopping_cart.war//org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:197)
... 67 more

答案1

得分: 3

当您拥有以下字段时:

@Column(name = "date_added", nullable = false, updatable=false, columnDefinition = "DATETIME DEFAULT CURRENT_TIMESTAMP")
@Temporal(value = TemporalType.TIMESTAMP)
private Date dateAdded;

如果不将 dateAdded 设置为适当的值(因此将其保留为 null),会导致所述的 ConstraintViolationException。因此,在初始化用户时,您需要设置 dateAdded,通常我会在构造函数或通过JPA注释来执行,但您也可以手动执行:

[...]
user.getPerson().setDateAdded(new Date());
user.setUserGroup(userGroup); // 为新用户分配该组
[...]

编辑:

因为我懒惰并且想要自动化事务,我大多数情况下使用注释来自动更新日期。我特别不喜欢特定于供应商的解决方案,因此通常使用JPA:

public class Person {
    // ...
    
    @PrePersist
    public void prePersist() {
        dateAdded = new Date();
    }
}

虽然Hibernate或Spring中有更复杂的解决方案,但效果始终相同:使用基于注释的机制,您不再需要手动设置 dateAdded

英文:

When you are having the field

@Column(name = &quot;date_added&quot;, nullable = false, updatable=false, columnDefinition = &quot;DATETIME DEFAULT CURRENT_TIMESTAMP&quot;)
@Temporal(value = TemporalType.TIMESTAMP)
private Date dateAdded;

not setting dateAdded to a proper value (and therefore leaving it null) causes said ConstraintViolationException. So, on initializing the user you need to set dateAdded which I usually do in a constructor or via JPA annotations but you can also do that manually:

[...]
user.getPerson().setDateAdded(new Date());
user.setUserGroup(userGroup); // Assign the new user this group
[...]

Edit:

Because I am lazy and I want to automate things I mostly use annotations for auto-updates of dates. I particular don't like vendor specific solutions so I use JPA normally:

public class Person {
// ...
@PrePersist
public void prePersist() {
dateAdded = new Date();
}
}

although there are more sophisticated solutions for Hibernate or Spring out there, but the effect is always the same: Using the annotation based mechanism you don't need to set dateAdded manually anymore.

huangapple
  • 本文由 发表于 2020年9月1日 15:38:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/63683318.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定