列不能为null无法插入

时间:2013-05-09 12:53:20

标签: java hibernate hibernate-mapping

亲爱的开发人员。

我会问你一个我认为很难为我解决的问题,因为我不知道答案的基本原因,          我的意思是说??我们来看看吧。 JBoss文档中的关联没有得到全面的答案:为什么我应该使用JoinTable而不是Foreign Key ,我不完全理解映射是如何工作的,                   这是什么意思?我知道什么是AssociationToMany或ManyToOne等协会,以及它们的目标是什么,但它们如何工作以及彼此协作不需要双向的答案或单向或joinTable或关联,我想有链接,我可以找到有关我的两个问题的完整信息:

1)为什么我应该使用JoinTable而不是外键 ????

2)实体如何工作以及彼此协作(没有解释什么是多个等等关联以及双向或单向关联)???

所以,我有一段代码,因为误解,我只是试图插入数据我是MYSQL数据库:Name_INSTITUTION和TYPE_NAME(机构类型):*

  • 我的实体类:

    @Entity 
    @Table(name="INSTITUTION")
    
    public class Institution implements Serializable{
    
    private static final long serialVersionUID = -7636394097858726922L;
    
    
    private int Id;
    
        @Id
        @GeneratedValue(strategy=IDENTITY)
        @Column(name="ID")
        public int getId() {
            return Id;
        }
        public void setId(int id) {
            Id = id;
        }
    
    
    private int Version;
    
        @javax.persistence.Version
        @Column(name="VERSION")
        public int getVersion() {
            return Version;
        }
        public void setVersion(int version) {
            Version = version;
        }
    
    
    private String Name_Institution;
    
        @Column(name="NAME_INSTITUTION")
        public String getName_Institution() {
            return Name_Institution;
        }
        public void setName_Institution(String name_Institution) {
            Name_Institution = name_Institution;
        }
    
    
    private Type type_inInstitution;
    
        @ManyToOne  
        @Cascade(org.hibernate.annotations.CascadeType.ALL)
        @JoinTable(name="TYPE_INSTITUTION", 
                                        joinColumns=@JoinColumn(name="INSTITUTION_ID"),
                                        inverseJoinColumns=@JoinColumn(name="TYPE_ID"))
        public Type getType_inInstitution() {
            return type_inInstitution;
        }
        public void setType_inInstitution(Type type_inInstitution) {
            this.type_inInstitution = type_inInstitution;
        }
    

    }

  • 我的第二个实体类:

    @Entity
    @Table(name="TYPE")
    
    public class Type implements Serializable {
    
    
    private static final long serialVersionUID = -4246217431412815552L;
    
    private String type;
    
        public Type(){}
    
        public Type(String type) {
        this.type = type;   
    
        }       
    
    private int Type_Id;
    
        @Id
        @GeneratedValue(strategy=IDENTITY)
        @Column(name="ID")
        public int getType_Id() {
            return Type_Id;
        }
        public void setType_Id(int type_Id) {
            Type_Id = type_Id;
        }
    
    
    private String Type_Name;
    
        @Column(name="TYPE_NAME")
        public String getType_Name() {
            return Type_Name;
        }
    
        public void setType_Name(String type_Name) {
            Type_Name = type_Name;
        }
    
    
    private int Version;
    
        @Version
        @Column(name="VERSION")
        public int getVersion() {
            return Version;
        }
        public void setVersion(int version) {
            Version = version;
        }
    
    
    
    private  Set<Institution> set_Institution_inType = new HashSet<Institution>();
    
        @OneToMany
        @JoinTable(name="TYPE_INSTITUTION",                                     joinColumns=@JoinColumn(name="TYPE_ID"),                                            inverseJoinColumns=@JoinColumn(name="INSTITUTION_ID"))
        public Set<Institution> getSet_Institution_inType() {
            return set_Institution_inType;
        }
        public void setSet_Institution_inType(Set<Institution> set_Institution_inType) {
            this.set_Institution_inType = set_Institution_inType;
        }
    
        public void addType(Institution institution) {
            institution.setType_inInstitution(this);
                   getSet_Institution_inType().add(institution);
    
        }
    

    }

    DAO课程:

    @Repository("daoInsertDataInterface")
    @Transactional
    
    public class InsertDataService implements DaoInsertDataInterface{
    
    private org.apache.commons.logging.Log log=  LogFactory.getLog(InsertDataService.class);
    
    private SessionFactory sessionFactory;
    
        public SessionFactory getSessionFactory() {
            return sessionFactory;
        }
    
        @Resource(name="sessionFactory")
        public void setSessionFactory(SessionFactory sessionFactory) {
            this.sessionFactory = sessionFactory;
        }
    
    
    @Override
    public Institution insertData(Institution institution) {
        sessionFactory.getCurrentSession().saveOrUpdate(institution);
        log.info(institution.getId());
        return institution;
    
    }
    

    }

  • 我的metada配置:

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName"><value>${jdbc.driverClassName}</value></property>
    <property name="url"><value>${jdbc.connectionValues}</value></property>
    <property name="username"><value>${jdbc.userName}</value></property>
    <property name="password"><value>${jdbc.password}</value></property>
    </bean>
    
    
    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    <property name="sessionFactory" ref ="sessionFactory"/>
    </bean>
    
    <context:property-placeholder location="connection.properties"/>
    
    <tx:annotation-driven transaction-manager="transactionManager"/>
    
    <context:component-scan base-package="edu.demidov.dom, edu.demidov.dao" />
    
    <context:annotation-config />
    
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="dataSource" ref ="dataSource"/>
    <property name="packagesToScan" value="edu.demidov.dom"/>
    <property name="hibernateProperties">
    <props>
    <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
    <prop key="hibernate.max_fetch_depth">3</prop>
    <prop key="hibernate.jdbc.fetch_size">50</prop>
    <prop key="hibernate.jdbc.batch_size">10</prop>
    <prop key="hibernate.show_sql">true</prop>
    </props>
    </property>
    
    </bean>
    

  • 错误:

  

INFO:org.springframework.beans.factory.xml.XmlBeanDefinitionReader -   从类路径资源加载XML bean定义   [app-context.xml]信息:   org.springframework.context.annotation.ClassPathBeanDefinitionScanner    - JSR-330&#39; javax.inject.Named&#39;找到并支持组件扫描的注释INFO:   org.springframework.context.support.GenericXmlApplicationContext -   清爽   org.springframework.context.support.GenericXmlApplicationContext@c93274:   启动日期[Thu May 09 11:38:23 EDT 2013];上下文层次结构的根   信息:   org.springframework.beans.factory.config.PropertyPlaceholderConfigurer    - 从类路径资源[connection.properties] INFO中加载属性文件:   org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor    - JSR-330&#39; javax.inject.Inject&#39;找到并支持自动装配INFO的注释:   org.springframework.beans.factory.support.DefaultListableBeanFactory -   在实例中预先实例化单身人士   org.springframework.beans.factory.support.DefaultListableBeanFactory@1b9c2f0:   定义bean   [数据源,transactionManager的,org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor #0,org.springframework.transaction.config.internalTransactionAdvisor,daoInsertDataInterface,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context .annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,的sessionFactory,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor];

     

工厂层次结构的根Hibernate:插入TYPE(TYPE_NAME,   VERSION)值(?,?)WARN:org.hibernate.util.JDBCExceptionReporter    - SQL错误:1048,SQLState:23000错误:org.hibernate.util.JDBCExceptionReporter - 列&#39; TYPE_NAME&#39;不能   be null线程中的异常&#34; main&#34;   org.hibernate.exception.ConstraintViolationException:不能   insert:[edu.demidov.dom.Type] at   org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:96)     在   org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)     在   org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:64)     在   org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2327)     在   org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2834)     在   org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:71)     在org.hibernate.engine.ActionQueue.execute(ActionQueue.java:273)at at   org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:320)     在   org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:203)     在   org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:129)     在   org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:210)     在   org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:195)     在   org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:117)     在   org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)     在   org.hibernate.impl.SessionImpl.fireSaveOrUpdate(SessionImpl.java:685)     在org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:677)     在   org.hibernate.engine.CascadingAction $ 5.cascade(CascadingAction.java:252)     在org.hibernate.engine.Cascade.cascadeToOne(Cascade.java:392)at   org.hibernate.engine.Cascade.cascadeAssociation(Cascade.java:335)at at   org.hibernate.engine.Cascade.cascadeProperty(Cascade.java:204)at at   org.hibernate.engine.Cascade.cascade(Cascade.java:161)at   org.hibernate.event.def.AbstractSaveEventListener.cascadeBeforeSave(AbstractSaveEventListener.java:450)     在   org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:282)     在   org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:203)     在   org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:129)     在   org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:210)     在   org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:195)     在   org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:117)     在   org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)     在   org.hibernate.impl.SessionImpl.fireSaveOrUpdate(SessionImpl.java:685)     在org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:677)     在org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:673)     在   edu.demidov.dao.InsertDataService.insertData(InsertDataService.java:32)     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at   sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)     在   sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)     在java.lang.reflect.Method.invoke(Method.java:601)at   org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)     在   org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)     在   org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)     在   org.springframework.transaction.interceptor.TransactionInterceptor $ 1.proceedWithInvocation(TransactionInterceptor.java:96)     在   org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)     在   org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)     在   org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)     在   org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)     在$ Proxy22.insertData(未知来源)at   edu.demidov.dao.AppTEst.main(AppTEst.java:22)   引起:   com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:   栏目&#39; TYPE_NAME&#39;不能为空   sun.reflect.NativeConstructorAccessorImpl.newInstance0(本机方法)     在   sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)     在   sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)     在java.lang.reflect.Constructor.newInstance(Constructor.java:525)     在com.mysql.jdbc.Util.handleNewInstance(Util.java:411)at   com.mysql.jdbc.Util.getInstance(Util.java:386)at   com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1041)at at   com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4120)at at   com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4052)at at   com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2503)at at   com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2664)at at   com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2815)at   com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2155)     在   com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2458)     在   com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2375)     在   com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2359)     在   org.hibernate.id.IdentityGenerator $ GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:94)     在   org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:57)     ... 44更多SS

谢谢你们,伙计们。

1 个答案:

答案 0 :(得分:2)

  

为什么我应该使用JoinTable insted外键?

你不应该。你有选择。如果您更喜欢使用连接表,请使用连接表。如果您更喜欢使用连接列(子表中的外键),请使用连接列。如果您已经存在无法更改的架构,请选择与现有架构对应的选项。

  

实体如何工作并相互协作

我不确定你的意思。如果实体学校与实体教师有OneToMany关联,当您从课程中获得学校并要求其教师时,Hibernate将为您从数据库加载它们。如果您将教师添加到学校教师的集合中,Hibernate将为您填充连接列或连接表。目标只是操纵对象,就好像它们是存储在内存中的简单对象一样,并且加载Hibernate并从/向数据库保存它们。

现在关于问题的例外和标题,异常消息清楚地说明了这一点:

  

插入TYPE(TYPE_NAME,VERSION)值(?,?)WARN:org.hibernate.util.JDBCExceptionReporter - SQL错误:1048,SQLState:23000错误:org.hibernate.util.JDBCExceptionReporter - 列'TYPE_NAME'不能是空的

您正在尝试使用空名称插入类型为Type的Ant(具有错误选择的名称!)。并且数据库列不会为null。所以你得到了这个例外。如果null是有效的类型名称,则更改表定义,或修复代码以确保不尝试插入空名称。

此外,尊重Java命名约定。你的代码真的很难读。