面对org.hibernate.exception.ConstraintViolationException的问题:

时间:2015-12-17 06:26:44

标签: hibernate hibernate-mapping

我遇到了Hibernate映射的问题。我正在使用oracle数据库。请查看代码,请帮我解决此问题。

模型类:

package com.model;

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

    @Entity
    @Table(name="emp")
    public class Employee {

        @Id
        @GeneratedValue(strategy=GenerationType.IDENTITY)
        @Column(name="eno")
        int empid;

        @Column(name="name")
        String name;

        @ManyToOne()
        @JoinColumn(name="deptid",nullable=false)
        Department dept;

        public int getEmpid() {
            return empid;
        }
        public void setEmpid(int empid) {
            this.empid = empid;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public Department getDept() {
            return dept;
        }
        public void setDept(Department dept) {
            this.dept = dept;
        }

    }

package com.model;

import java.util.Set;

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

@Entity
@Table(name="dept")
public class Department {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="deptid")
    int deptid;

    @Column(name="deptname")
    String deptname;

    @OneToMany(mappedBy="dept")
    Set<Employee> empset;

    public int getDeptid() {
        return deptid;
    }
    public void setDeptid(int deptid) {
        this.deptid = deptid;
    }
    public String getDeptname() {
        return deptname;
    }
    public void setDeptname(String deptname) {
        this.deptname = deptname;
    }
    public Set<Employee> getEmpset() {
        return empset;
    }
    public void setEmpset(Set<Employee> empset) {
        this.empset = empset;
    }
}

配置文件:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <!-- Database connection settings -->
        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
        <property name="connection.url">jdbc:oracle:thin:@localhost:1521:XE</property>
        <property name="connection.username">user_name</property>
        <property name="connection.password">password</property>

        <property name="connection.pool_size">1</property>
        <property name="dialect">org.hibernate.dialect.OracleDialect</property>
        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">validate</property>

    <mapping class="com.model.Employee"/>
    <mapping class="com.model.Department"/>

    </session-factory>
</hibernate-configuration>

测试类:

package com.demo;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import com.model.Department;
import com.model.Employee;

public class HibernateTest {

    public static void main(String[] args) {
        Configuration cfg = new Configuration();
        cfg.configure();
        SessionFactory sf = cfg.buildSessionFactory();
        Session sess = sf.openSession();
        Transaction tx = sess.beginTransaction();

        Department dept1 = new Department();
        dept1.setDeptname("aaa");

        sess.save(dept1);

        Employee emp1 = new Employee();
        emp1.setName("aaa");
        emp1.setDept(dept1);

        sess.save(emp1);
        tx.commit();
        sess.close();
    }
}

db表结构: create table emp(eno number(4)primary key,name varchar2(10),deptid number(5)forign key references dept(deptid));

create table emp(deptid number(5)primary key,deptname varchar2(10));

我得到的错误是:

Exception in thread "main" org.hibernate.exception.ConstraintViolationException: could not execute statement
    at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:129)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:190)
    at org.hibernate.id.insert.AbstractSelectingDelegate.performInsert(AbstractSelectingDelegate.java:61)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3032)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3558)
    at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:98)
    at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:490)
    at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:195)
    at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:179)
    at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:214)
    at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:324)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:288)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:194)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:209)
    at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)
    at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
    at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:715)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:707)
    at org.hibernate.internal.SessionImpl.save(SessionImpl.java:702)
    at com.demo.HibernateTest.main(HibernateTest.java:23)
Caused by: java.sql.SQLException: ORA-01400: cannot insert NULL into ("VASAVI"."DEPT"."DEPTID")

    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:331)
    at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:288)
    at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:743)
    at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:216)
    at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:955)
    at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1169)
    at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3285)
    at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:3368)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:187)
    ... 21 more

2 个答案:

答案 0 :(得分:0)

我已经使用hibernate.properties测试了MySQL数据库上的持久化类。一切都很完美(没有任何错误)。所以,我认为,您需要使用

重新创建数据库模式
class TestSMS
    {
        public static string strIp = "10.00.105.00";
        public static int Port = 1009;
        //-----------------connect------------------//


        public static Socket Connect(string host, int port)
        {
            Socket socket = new Socket(AddressFamily.InterNetwork,
                SocketType.Stream,
                ProtocolType.Tcp);

            Console.WriteLine("Establishing Connection to {0}",
                host);
            socket.Connect(host, port);
            clsError.LogError("TestSMS:Connect()", "Connection established");
            return socket;
        }



        //---------------End connect----------------//

        //-------------------send--------------------//



        public static int SendReceiveTest(Socket server,string Message)
        {
            byte[] connectionString = Encoding.UTF8.GetBytes("CON^`!XML^`!ABCD#END#");
            byte[] msg = Encoding.UTF8.GetBytes(Message);
            byte[] bytes = new byte[1024];
            string response = string.Empty;
            int byteCount = 0;
            int i = 0;
            try
            {
                // Blocks until send returns.
                 i = server.Send(connectionString, connectionString.Length, SocketFlags.None);
                clsError.LogError("TestSMS:SendReceiveTest()", "Connection string sent");

                // Get reply from the server.
                 byteCount = server.Receive(bytes, server.Available,
                                                   SocketFlags.None);
                 if (byteCount > 0)
                 {
                     response = Encoding.UTF8.GetString(bytes);
                     if (response.IndexOf("CON!0") != 0)
                     {
                          i = server.Send(msg, msg.Length, SocketFlags.None);

                         clsError.LogError("TestSMS:SendReceiveTest()", "Message data sent");
                         byteCount = server.Receive(bytes, server.Available,
                                                   SocketFlags.None);
                         response = Encoding.UTF8.GetString(bytes);

                         if ((response.ToString().IndexOf("ACK!1") == 0) || (response.ToString().IndexOf("ACK!MSGSTATUS=TRUE") == 0))
                         {
                             clsError.LogError("TestSMS:SendReceiveTest()", "Message sent successfully:  " + response);
                         }
                         //log

                     }
                     else
                     {
                         clsError.LogError("TestSMS:SendReceiveTest()", "Could not handshake with SMS Server");
                     }

                 }
                 else
                 {
                     clsError.LogError("TestSMS:SendReceiveTest()", "No Acknowledgement recieved");
                 }
            }
            catch (SocketException e)
            {
                clsError.LogError("TestSMS:SendReceiveTest()", e.Message.ToString());
                return (e.ErrorCode);
            }
            return 0;
        }



        //-----------------End send------------------//

        static void Main(string[] args)
        {  

            try
            {
                string strXmlFormat = " MSG^`!<DEPT>IPL</DEPT><APPID>TLC</APPID><MOBILE>918879440021</MOBILE><DEPTMSGID>14092111115JH21075</DEPTMSGID><MESSAGE>This is a test message</MESSAGE><FROMDATETIME></FROMDATETIME><TODATETIME></TODATETIME><NODELIVERYTIMEFROM>2200</NODELIVERYTIMEFROM><NODELIVERYTIMETO>0700</NODELIVERYTIMETO><HTTPMODE>S</HTTPMODE><REMARKS></REMARKS><REMARKS1></REMARKS1><REMARKS2></REMARKS2><TRN_GENERATE_TIMESTAMP>2015-12-10 16:48:54 </TRN_GENERATE_TIMESTAMP>#END#";
                clsError.LogError("Inside Main:Msg in XML format", strXmlFormat);
                Socket Socket;
                Socket = TestSMS.Connect(TestSMS.strIp, TestSMS.Port);

                TestSMS.SendReceiveTest(Socket, strXmlFormat);


            }
            catch (Exception ex)
            {
                clsError.LogError("Inside Main:Main()", ex.Message.ToString());
                throw ex;

            }

        }



    }

答案 1 :(得分:0)

如果要在具有唯一索引或约束的列中插入值,并且此列的插入值已存在于另一行中,则始终显示此错误。重新创建数据库模式。 更改配置文件

<property name="hibernate.hbm2ddl.auto">validate</property> 

<property name="hibernate.hbm2ddl.auto">create</property>