处理JPA的@Column(unique = true)异常

时间:2017-11-08 10:02:10

标签: java hibernate

我已经搜索了stackoverflow并尝试按照过去的答案捕获不同的异常,但没有任何效果。

我的模型类是:

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    @Column(nullable = false)
    private String name;

    @Column(nullable = false, unique = true)
    private String username;

    @Column(nullable = false)
    private String password;
    ...
    ...
}

如果用户名尚不存在,则代码有效。 但是,每当用户尝试添加具有db中已存在的用户名的用户时,它就会抛出异常@Column(nullable = false)。我的目的是捕获此错误并显示“重复用户名”对话框。 但我无法抓住它。 这是我将用户添加到db:

的方法
@Override
public void addUser(User user) {
    SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
    Session session = sessionFactory.openSession();
    try {

        session.beginTransaction();
        session.save(user);
    }  catch (PersistenceException  e) {
        System.out.println("username already exist");
    }

    session.getTransaction().commit();
    session.close();
    sessionFactory.close();

}

如前所述,我已经“点击并试用”了许多例外类,但似乎没有任何效果。它显示以下错误:

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 (id, password, username) values (?, ?, ?)
Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:149)
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:157)
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:164)
    at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1443)
    at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:493)
    at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3207)
    at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2413)
    at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:467)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:156)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$100(JdbcResourceLocalTransactionCoordinatorImpl.java:38)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:231)
    at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:68)
    at com.ultranet.servicesImpl.UserServiceImpl.addUser(UserServiceImpl.java:57)
    at com.ultranet.main.DriverClass.main(DriverClass.java:20)
Caused by: org.hibernate.exception.ConstraintViolationException: could not execute statement
    at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:59)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:178)
    at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:45)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3013)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3513)
    at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:89)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:589)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:463)
    at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:337)
    at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
    at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1437)
    ... 10 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry 'admint' for key 'UK_jreodf78a7pl5qidfh43axdfb'
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
    at com.mysql.jdbc.Util.getInstance(Util.java:381)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1015)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3491)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3423)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1936)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2060)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2542)
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1734)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2019)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1937)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1922)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:175)
    ... 19 more

那么,我如何捕获此异常以便我可以显示用户友好的消息? P.s:我尝试捕获的一些例外是:

java.sql.SQLException;
java.sql.SQLIntegrityConstraintViolationException;
javax.persistence.EntityExistsException;
javax.persistence.PersistenceException;
javax.transaction.RollbackException;
org.hibernate.HibernateException;
org.hibernate.exception.ConstraintViolationException;
org.springframework.dao.DataIntegrityViolationException;
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException;

3 个答案:

答案 0 :(得分:1)

数据库异常应始终是致命的,这就是它们是运行时的原因。从我的角度来看,在尝试创建用户之前,您应该验证自己是否已经存在具有该用户名的用户。然后,您可以生成一个自定义异常,以便由更高的代码捕获以呈现给最终用户。

答案 1 :(得分:1)

首先," unique = true"注释在运行时不会帮助您。它描述了数据库模式的外观。模式映射器读取此注释并确保该列是唯一的。

在您的情况下,您尝试插入无效数据,并且您得到了一个" MySQLIntegrityConstraintViolationException"。要提取有关问题的更多详细信息并不容易。无论如何,持久化失败并将当前的持久性上下文置于失败/回滚状态。通常,你不想在这里结束。

最好添加一个验证步骤以完全避免这种情况。在数据库中查询此用户名 - 如果已存在,则显示验证问题。如果有两个进程试图同时插入相同的用户名,你仍然会遇到初始问题,但如果在持久化之前进行验证,则可能性很小。

答案 2 :(得分:0)

我认为你的捕捉功能运作良好,但问题是commit之后:
session.getTransaction().commit(); 您应该在catch块中回滚此事务,但不要提交。

您可以检查代码的哪一行抛出该异常。在你错误的日志中,它说它是UserServiceImpl.addUser(UserServiceImpl.java:57)