java - 使用 Hibernate 和 Spring 的一对多映射

标签 java spring hibernate postgresql

我正在尝试使用外键创建两个连接表 ConceptModelDetails 和 Instructions。以下是我的模型类:

概念模型详细信息:

package com.assignment.model;

@Entity
@Table(name="conceptModelDetails")
public class ConceptModelDetails {
    @Id @GeneratedValue(strategy=GenerationType.AUTO)
    private int instructionsId;
    private String operationType;
    private String conceptModelID;
    private String requestor;
    private String status;
    private Timestamp requestDateTime;
    private Timestamp lastExecutedDateTime;
    private Timestamp completedDateTime;
    @OneToMany(cascade=CascadeType.ALL, mappedBy="conceptModelDetails")
    private Set<Instructions> instructions; 

    public ConceptModelDetails() {}     
}

和说明:

package com.assignment.model;

@Entity
@Table(name="instructions")
public class Instructions {
    @Id
    @GeneratedValue
    private int Sno;
    private String instruction;
    @ManyToOne
    @JoinColumn(name="instructionsId")
    private ConceptModelDetails conceptModelDetails;
}

下面是applicationContext.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop-4.1.xsd 
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd 
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.1.xsd 
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">

    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">

        <property name="driverClassName" value="org.postgresql.Driver" />
        <property name="url" value="jdbc:postgresql://192.168.1.79:5432/test" />
        <property name="username" value="postgres" />
        <property name="password" value="admin" />
    </bean>
    <bean id="objDAO" class="com.assignment.dao.impl.ConceptModelDAOImpl">
        <property name="sessionFactory" ref="sessionfactory" />

    </bean>
    <bean id="sessionfactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="packagesToScan" value="com.assignment.model"></property>
        <property name="annotatedClasses">
            <list>
                <value>com.assignment.model.ConceptModelDetails</value>
                <value>com.assignment.model.Instructions</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.cache.use_second_level_cache">false</prop>
            </props>
        </property>

    </bean>
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionfactory" />
    </bean>
    <tx:annotation-driven transaction-manager="transactionManager" />

</beans>

和 Controller :

    @RequestMapping(value = "/myCntrl", method = RequestMethod.POST)
    public String handler(HttpServletRequest request) {
        System.out.println("handler");
        // System.out.println(request.getParameter("conceptID"));
        // System.out.println(request.getParameter("operationType"));
        String[] operations = request.getParameterValues("operations");
        Date date = new Date();
        Timestamp time = new Timestamp(date.getTime());
        ConceptModelDetails conceptModelDetails = new ConceptModelDetails();
        conceptModelDetails
                .setConceptModelID(request.getParameter("conceptID"));
        conceptModelDetails.setOperationType(request
                .getParameter("operationType"));
        conceptModelDetails.setRequestor(request.getParameter("requestor"));
        conceptModelDetails.setRequestDateTime(time);
        ApplicationContext context = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        System.out.println("yo");
        ConceptModelDAO obj = (ConceptModelDAO)context.getBean("objDAO");
        System.out.println("no");
        Instructions instructions = new Instructions();
        for(int i = 0; i < operations.length; i++){
        instructions.setInstruction(operations[i]);
        obj.addInstructions(instructions);
        }
        obj.add(conceptModelDetails);           


        return "success";

    }

我运行这段代码时遇到的问题是:

  1. 两个表使用相同的 hibernate_sequence。

  2. 如以下屏幕截图所示,外键未映射到指令表中。

Tables

代码有什么问题请高手指点。我是 hibernate 和 spring 的新手,所以我希望得到详细的解释。提前致谢。

最佳答案

1) 当 JPA 规范未提供生成器时,您正在使用 hibernate 默认提供的全局序列生成器。

改变如下。对每个类具有不同序列的两个类执行此操作。

@Entity
@SequenceGenerator(name="PRIVATE_SEQ", sequenceName="private_sequence")
public class ConceptModelDetails {
    @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator="PRIVATE_SEQ")
    private int instructionsId;

2) 这里 Instructions 类拥有关系和 因此,在保存 Instructions 对象之前,您应该将 ConceptModelDetails 对象设置为 Instructions 对象。

ConceptModelDetails cmd1 = new ConceptModelDetails();

Instructions i = new Instructions()
i.setConceptModelDetails(cmd1);
....

然后保存Instructions对象i

希望这对您有所帮助。

关于java - 使用 Hibernate 和 Spring 的一对多映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33931715/

相关文章:

java - JPA 的@UniqueConstraint 注释似乎不能保证唯一性

java - 数组递增和 i++ 问题

java 日历格式

spring - SFTP上传文件权限被拒绝

spring - JHipster:CORS 在表单登录时失败(实际请求,不是飞行前)

java - 蓝图服务列表 : Wait for all services

java - Spring 安全: Unable to autowired DAO in the UserDetailsService class

java - 如何在hql上使用 'group by'?

java - 如何在没有 JMF 的情况下用 Java 创建媒体播放器?

java - 如何从Android上的sharedPreferences获取多个值?