简体   繁体   中英

One to Many mapping using Hibernate and Spring

I am trying to create two join tables ConceptModelDetails and Instructions using a foreign key. Following are my model classes:

ConceptModelDetails:

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() {}     
}

and Instuctions:

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;
}

Following is 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>

and 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";

    }

Problems when I run this code are:

  1. Same hibernate_sequence is used for both the tables.

  2. Foreign key is not mapped in the Instruction table as seen in the following screenshot.

表

Please guide what is wrong with the code. I am new to hibernate and spring, so I'd appreciate a detailed explanation. Thanks in advance.

1) You are using the Global sequence generator that hibernate provide by default when no generator is provided as specifed by the JPA Spec.

Change it as follows. Do this to the both of the classes with different sequences for each class.

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

2) Here Instructions class owns the relationship and therefore you should set ConceptModelDetails object to the Instructions object before saving the Instructions object.

ConceptModelDetails cmd1 = new ConceptModelDetails();

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

Then save the Instructions object i

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM