Announcement Announcement Module
Collapse
No announcement yet.
JPA hibernate mapping error Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • JPA hibernate mapping error

    Hi all,

    I have an application where i want to insert data in to database.
    I have two tables Patients and Users.which are like this:

    patient:
    @Entity
    @Table(name = "PATIENT")
    public class Patient {

    private Users users;

    @ManyToOne
    @JoinColumn(name="PT_PROVIDER_ID")
    public Users getUsers(){
    return users;
    }
    public void setUsers(Users users){
    this.users = users;
    }

    @Id
    @Column(name = "PT_ID")
    @GeneratedValue(generator="patientseq")
    @SequenceGenerator(name = "patientseq",sequenceName="patient_seq", allocationSize = 1)

    private int id;

    @Column(name = "PT_FNAME")
    private String fname;

    @Column(name = "PT_MNAME")
    private String mname;

    @Column(name = "PT_LNAME")
    private String lname;

    //getter and setter methods
    }

    Users:
    @Entity
    @Table(name = "USERS")
    public class Users {

    private List<Patient> patient;

    @OneToOne(mappedBy="users",
    cascade=CascadeType.ALL,
    targetEntity=Patient.class)
    public List<Patient> getPatient(){
    return patient;
    }
    public void setPatient(List<Patient> patient){
    this.patient = patient;
    }

    @Id
    @Column(name = "USER_ID")
    @GeneratedValue(strategy = SEQUENCE, generator = "user_seq")
    @SequenceGenerator(name = "user_seq", allocationSize = 1)
    private int id;

    @Column(name = "USER_FNAME")
    private String firstName = null;
    //getter and setter methods
    }


    ApplicationContext.xml file:
    <beans>
    <bean id="patientDao" class="com.ctos.impl.JpaPatientDao">
    <property name="entityManagerFactory" ref="entityManagerFactory"/>
    </bean>

    <bean id="usersDao" class="com.ctos.impl.JpaUsersDao">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>

    <bean id="entityManagerFactory"
    class="org.springframework.orm.jpa.LocalContainerE ntityManagerFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="jpaVendorAdapter">
    <bean class="org.springframework.orm.jpa.vendor.Hibernat eJpaVendorAdapter">
    <property name="showSql" value="true" />
    <property name="generateDdl" value="true" />
    <property name="databasePlatform" value="org.hibernate.dialect.PostgreSQLDialect" />
    </bean>
    </property>
    </bean>

    <bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverM anagerDataSource">
    <property name="driverClassName" value="org.postgresql.Driver" />
    <property name="url" value="jdbcostgresql://localhost/ctos" />
    <property name="username" value="postgres" />
    <property name="password" value="test" />
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionM anager">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
    <property name="dataSource" ref="dataSource" />
    </bean>

    <tx:annotation-driven/>
    <bean class="org.springframework.dao.annotation.Persiste nceExceptionTranslationPostProcessor"/>
    </beans>

    DB schema:
    TABLE users
    (
    user_id integer NOT NULL DEFAULT nextval('users_seq'::regclass),
    user_fname character varying(25) NOT NULL)

    TABLE patient
    (
    pt_id integer NOT NULL DEFAULT nextval('patient_seq'::regclass),
    pt_provider_id integer,CONSTRAINT ptproviderfk FOREIGN KEY (pt_provider_id)
    REFERENCES users (user_id) MATCH FULL
    ON UPDATE NO ACTION ON DELETE NO ACTION
    )

    One user has many patients. so the mapping.

    The application is throwing up error and is not working.
    This is the log file:
    Caused by: javax.persistence.PersistenceException: [PersistenceUnit: ctos] Unable to build EntityManagerFactory
    at org.hibernate.ejb.Ejb3Configuration.buildEntityMan agerFactory(Ejb3Configuration.java:677)
    at org.hibernate.ejb.HibernatePersistence.createConta inerEntityManagerFactory(HibernatePersistence.java :132)
    at org.springframework.orm.jpa.LocalContainerEntityMa nagerFactoryBean.createNativeEntityManagerFactory( LocalContainerEntityManagerFactoryBean.java:224)
    at org.springframework.orm.jpa.AbstractEntityManagerF actoryBean.afterPropertiesSet(AbstractEntityManage rFactoryBean.java:291)
    at org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.invokeInitMethods(Abstr actAutowireCapableBeanFactory.java:1369)
    at org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.initializeBean(Abstract AutowireCapableBeanFactory.java:1335)
    ... 52 more
    Caused by: org.hibernate.MappingException: Could not determine type for: java.util.List, at table: USERS, for columns: [org.hibernate.mapping.Column(patient)]
    at org.hibernate.mapping.SimpleValue.getType(SimpleVa lue.java:269)
    at org.hibernate.mapping.SimpleValue.isValid(SimpleVa lue.java:253)
    at org.hibernate.mapping.Property.isValid(Property.ja va:185)
    at org.hibernate.mapping.PersistentClass.validate(Per sistentClass.java:440)
    at org.hibernate.mapping.RootClass.validate(RootClass .java:192)
    at org.hibernate.cfg.Configuration.validate(Configura tion.java:1121)
    at org.hibernate.cfg.Configuration.buildSessionFactor y(Configuration.java:1306)
    at org.hibernate.cfg.AnnotationConfiguration.buildSes sionFactory(AnnotationConfiguration.java:867)
    at org.hibernate.ejb.Ejb3Configuration.buildEntityMan agerFactory(Ejb3Configuration.java:669)
    ... 57 more

    Could somebody suggest me what to do and where am i going wrong?

    Thanks
    vinay

  • #2
    this might help

    make sure your List<...> is initialized to an implementation. e.g.
    Code:
    private List<Patient> patient = new ArrayList<Patient>();

    Comment


    • #3
      JPA hibernate mapping error: Exception

      Thanks fdemilde,

      But it seems not to be the only problem. I have searched this forum and found that the annotations should be used only for fields or getter methods in the POJO.I changed all my annotations to getter methods.

      I have implementd a propertyEditor sub class like this:

      public class patientPropertyEditor extends PropertyEditorSupport{

      protected final Log logger = LogFactory.getLog(getClass());


      public patientPropertyEditor(){

      }

      public void setAsText(String text)throws IllegalArgumentException{
      Integer Id = new Integer(text);
      super.setValue(Id);
      }

      }
      And bound it to my controller like this:
      protected void initBinder(HttpServletRequest request,ServletRequestDataBinder binder)
      throws Exception{
      binder.registerCustomEditor(Users.class,new patientPropertyEditor());
      }

      My Jsp has this code:
      <form:form method="POST" commandName="patient">
      ...............
      <td class="lblstyle"><label>Primary Provider <span>*</span> :</label></td>
      <td>
      <form:select path="id" >
      <form:option value="" label="-Select Provider-"/>
      <form:options items="${usersList}" itemValue="id" itemLabel="firstName"/>
      </form:select>
      &nbsp;
      <font color="red"><form:errors path="id"/></font>
      </td>
      ...........
      </form:form>


      NOw when i run the application the log file reports this problem:
      15:21:18,406 DEBUG JpaPatientDao:22 - Exception while inserting patientorg.springframework.dao.InvalidDataAccessAp iUsageException: detached entity passed to persist: com.ctos.model.Patient; nested exception is org.hibernate.PersistentObjectException: detached entity passed to persist: com.ctos.model.Patient


      What could be the problem.I would be really relieved to know the solution to this problem.

      Thanks
      vinay

      Comment


      • #4
        more info please

        please provide more details (within [ CODE ]...[/ CODE ] tags) of config files, view files, DAO, ...

        Comment


        • #5
          JPA hibernate mapping error etails

          I have the following files :
          Patient class:
          Code:
          @Entity
          @Table(name = "PATIENT")
          public class Patient {	
                  private int id;	
          	private Users users;	
          	private String fname;	
          
          @Id
          	@GeneratedValue(generator="patientseq")
          	@SequenceGenerator(name = "patientseq",sequenceName="patient_seq", allocationSize = 1)
          	@Column(name = "PT_ID")
          	public int getId() {
          		return id;
          	}
          	public void setId(int id) {
          		this.id = id;
          	}
          	
          	@ManyToOne
          	@JoinColumn(name="PT_PROVIDER_ID")
          	public Users getUsers(){
          		return users;
          	}
          	public void setUsers(Users users){
          		this.users = users;
          	}	
          	
          	@Column(name = "PT_FNAME")
          	public String getFname() {
          		return fname;
          	}
          	public void setFname(String fname) {
          		this.fname = fname;
          	}	
          }
          Users class
          Code:
          @Entity
          @Table(name = "USERS")
          public class Users {	
          	
          	private int id;
          	
          	private List<Patient> patient = new ArrayList<Patient>();
          
          	private String firstName = null;
          @Id
          	@GeneratedValue(strategy = SEQUENCE, generator = "user_seq")
          	@SequenceGenerator(name = "user_seq", allocationSize = 1)	
          	@Column(name = "USER_ID")	
          	public int getId() {
          		return id;
          	}
          	public void setId(int id) {
          		this.id = id;
          	}
          	
          	@OneToMany(mappedBy="users",
          			cascade=CascadeType.ALL,targetEntity=Patient.class)	
          	public List<Patient> getPatient(){
          		return patient;
          	}
          	public void setPatient(List<Patient> patient){
          		this.patient = patient;
          	}		
          	
          
          	@Column(name = "USER_FNAME")
          	public String getFirstName() {
          		return firstName;
          	}
          	public void setFirstName(String firstName) {
          		this.firstName = firstName;
          	}
          }
          The controller
          Code:
          public class newPatientController extends SimpleFormController{	
          public newPatientController(){
          			
          			setCommandClass(Patient.class);
          			setCommandName("patient");
          		}	
          protected void initBinder(HttpServletRequest request,ServletRequestDataBinder binder)
          		throws Exception{
          			logger.info("Init Binder");				
          			binder.registerCustomEditor(Users.class,new patientPropertyEditor());			
          		}
          
          		protected ModelAndView onSubmit(HttpServletRequest request,HttpServletResponse response,
          				Object command, BindException errors) throws Exception {	
          			
          			Patient patient = (Patient)command;				
          			boolean addPatient = this.patientDao.addPatient(patient);	
          			logger.info("Adding patient to  database....");
          			while(addPatient){
          				List<Patient> patientList = this.patientDao.getPatients();
          				request.setAttribute("patientList", patientList);
          				return new ModelAndView(getSuccessView(),"patientList",patientList);			
          			}
          	            return new ModelAndView(getFormView());
          		}	
          public void setPatientDao(PatientDao patientDao) {
          			this.patientDao = patientDao;
          		}			
          }
          JSP file
          Code:
          <form:form method="POST" commandName="patient">
          <table>
             						<tr>&nbsp;</tr>   	
             											
             						<tr>
             							<td class="lblstyle"><label>First Name <span>*</span> :</label></td>
             							<td>
             								<form:input path="fname" size="25" maxlength="25" />
             								&nbsp;
             								<font color="red"><form:errors path="fname"/></font>
             							</td>
          <tr>
             							<td class="lblstyle"><label>Primary Provider <span>*</span> :</label></td>
             							<td>
             								<form:select path="id" >  
             							    	<form:option value="" label="-Select Provider-"/>	
             							    	<form:options items="${usersList}" itemValue="id" itemLabel="firstName"/>	
             							    </form:select>	
             								&nbsp;  						
             								<font color="red"><form:errors path="id"/></font>
             							</td>
          </tr>
             </table>
          <table>
             				
             				<tr>
             						
             						<td><button name="Submit" >Submit</button>
             						<button name="Reset" >Reset</button></td>
             						
          				</tr>
             				</table>
          </form:form>
          Application context file
          Code:
          <beans>
          <bean id="patientDao" class="com.ctos.impl.JpaPatientDao">
          		<property name="entityManagerFactory" ref="entityManagerFactory"/>
          	</bean>	
          	
          <bean id="entityManagerFactory"
          		class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
          		<property name="dataSource" ref="dataSource" />		
          		<property name="jpaVendorAdapter">
          			<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
          				<property name="showSql" value="true" />
          				<property name="generateDdl" value="true" />
          				<property name="databasePlatform" value="org.hibernate.dialect.PostgreSQLDialect" />
          			</bean>
          		</property>						
          	</bean>
          	
          	<bean id="dataSource"
          		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
          		<property name="driverClassName" value="org.postgresql.Driver" />
          		<property name="url" value="jdbc:postgresql://localhost/ctos" />
          		<property name="username" value="postgres" />
          		<property name="password" value="test" />
          	</bean>
          
          	<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
          		<property name="entityManagerFactory" ref="entityManagerFactory" />
          		<property name="dataSource" ref="dataSource" />
          	</bean>
          
          	<tx:annotation-driven/>
          	<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
          
          </beans>
          DB schema extract(postgresql):
          CREATE TABLE patient
          (
          pt_id integer NOT NULL DEFAULT nextval('patient_seq'::regclass),
          CONSTRAINT patient_pkey PRIMARY KEY (pt_id),
          CONSTRAINT ptproviderfk FOREIGN KEY (pt_provider_id)
          REFERENCES users (user_id) MATCH FULL
          ON UPDATE NO ACTION ON DELETE NO ACTION
          )

          CREATE TABLE users
          (
          user_id integer NOT NULL DEFAULT nextval('users_seq'::regclass),
          user_fname character varying(25) NOT NULL,CONSTRAINT users_pkey PRIMARY KEY (user_id))

          I have provided onetomany mapping between user_id(users table) and pt_provider_id(patient table). ANd added a custom property editor to convert pt-provider_id form string value to integer.When i add the record in jsp i get an error in browser as:
          Code:
          org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Transaction marked as rollbackOnly
          	org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:465)
          
          The log file has this error:
          org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Transaction marked as rollbackOnly
          Its really taking alot of time and i am not able to understand whats the problem.I am new to JPA. Could you help me.

          Thanks
          vinay

          Comment


          • #6
            still more info required

            and could you provide web.xml and your persistence.xml as well. Maybe your dao could be usefull too. And which version of Spring you use?

            Comment


            • #7
              JPA hibernate mapping error etails

              Hi,

              The Web.xml file is a simple one with servlet name,servlet mapping,spring contextLoaderListener and context-param -contextConfigLocation to point to applicationContext.xml.

              Persistence.xml file is also simple:
              Code:
              <persistence-unit name="app" transaction-type="RESOURCE_LOCAL">
              		
              		<class>com.app.model.Users</class>			
              		<class>com.app.model.Locations</class>		
              		<class>com.app.model.States</class>
              		<class>com.app.model.Medications</class>
              		<class>com.app.model.Patient</class>	
              		
              	</persistence-unit>
              </persistence>
              The dao's implementation classes are :
              JpausersDaoImpl
              Code:
              public class JpaUsersDao extends JpaDaoSupport implements UsersDao{
              
              	@SuppressWarnings("unchecked")
              	@Override
              	public List<Users> getUsers() {
              		return getJpaTemplate()
              				.find("from Users u");
              	}
              	
              	@SuppressWarnings("unchecked")
              	@Override
              	public List<Users> getUsersByFirstName(String name) {
                      return getJpaTemplate().find("from Users as u where lower(u.firstName) like '" + name +"%'");
                      
              
              	}
              
              	@SuppressWarnings("unchecked")
              	@Override
              	public List<Users> getUsersById(int Id) {
                    return getJpaTemplate().find("from Users as u where u.id = " + Id);	   
              
              	}
              }
              JpaPatientsDaoImpl class
              Code:
              public class JpaPatientDao extends JpaDaoSupport implements PatientDao{
              
              	@Override
              	@Transactional
              	public boolean addPatient(Patient patient) {
              		boolean addition = false;
              		try{
              			getJpaTemplate().persist(patient);
              			addition = true;			
              		}
              		catch(Exception ex){
              			logger.debug("Exception while inserting patient" + ex);
              		}
              		return addition;
              	}
              
              	@SuppressWarnings("unchecked")
              	@Override	
              	public List<Patient> getPatients() {
              		return getJpaTemplate().find("from Patient as p");
              	}
              
              	@Override
              	public Patient getPatient(int setId) {
              		Patient getPatient = this.getJpaTemplate().find(Patient.class,setId);
              		return getPatient;
              	}
              
              	@SuppressWarnings("unchecked")
              	@Override
              	public List<Patient> getPatientById(int id) {
              		return getJpaTemplate().find("from Patient as p where p.id = " + id);
              	}
              
              	@Override
              	@Transactional
              	public void savePatient(Patient patient) {
              		Patient savedPatient = this.getJpaTemplate().merge(patient);
              		this.getJpaTemplate().flush();
              		patient.setId(savedPatient.getId());		
              	}
              
              }
              I am working with spring 3.0 framework but not yet on annotated controllers and stuff. Just the old spring style.That's not a problem i guess.

              I think the problem is either in the mapping of POJO's or probably in the call to customPropertyEditor(see previously posted code).I am not sure.Any guidance is very much appreciated.

              Thanks,
              vinay

              Comment


              • #8
                could you verify

                Could you check if specifying the <provider> inside your persistence.xml (
                Code:
                e.g.  
                 <persistence-unit name="persistenceUnit" transaction-type="RESOURCE_LOCAL">
                        <provider>org.hibernate.ejb.HibernatePersistence</provider>
                        <properties>
                            ....
                        </properties>
                    </persistence-unit>
                
                if you use Hibernate
                ) and specifying the
                the properties "persistenceXmlLocation" and "persistenceUnitName" of your LocalContainerEntityManagerFactoryBean, makes any difference?

                Comment


                • #9
                  JPA hibernate mapping error

                  I don't think the properties in persistence.xml file need to be set as the default would take them as configured in applicationContext.xml file (see the code posted earlier above).

                  I do not understand the source of the problem.I think though that it is from the mapping between the POJO and the DB schema.Any help is really appreciated , i have been on this thing for the past 5 days or so.

                  Thanks
                  vinay

                  Comment


                  • #10
                    might help

                    have you tried the provider inside the persistence.xml?

                    other thing I notice, in our projects we annotate the fields instead of the methods ... (we encountered issues when using annotations scattered amongst fields and methods... something I noticed inside your Users class)

                    Comment


                    • #11
                      JPA hibernate mapping error

                      Hi,

                      I have placed the model references properly in persistence.xml file.
                      Also i have changed all the annotations to the fields.
                      Still i get the error.
                      I strongly belive it has something to do with JPA mapping of POJO's.

                      Users is the parent class and Patients is the child. I have a foreign key in the child class.Is my JPA mapping right?

                      Thanks and Regards,
                      vinay

                      Comment


                      • #12
                        org.hibernate.MappingException: Could not determine type for:

                        I am also getting similar exception stack trace while running AbstractJpaTests. The only difference being that hibernate mapping exception is for different type. I tried debugging and found that ShadowingClassLoader tries to load 'truefalse-type.class' but fails to get it and throws ClassNotFoundException although 'TrueFalse-type.class' is there in hibernate3.jar on classpath. I am not sure whether it case mismatch in class name. Below is the stack trace.

                        Caused by: javax.persistence.PersistenceException: [PersistenceUnit: test] Unable to build EntityManagerFactory
                        at org.hibernate.ejb.Ejb3Configuration.buildEntityMan agerFactory(Ejb3Configuration.java:677)
                        at org.hibernate.ejb.HibernatePersistence.createEntit yManagerFactory(HibernatePersistence.java:126)
                        at javax.persistence.Persistence.createEntityManagerF actory(Persistence.java:83)
                        at org.springframework.orm.jpa.LocalEntityManagerFact oryBean.createNativeEntityManagerFactory(LocalEnti tyManagerFactoryBean.java:91)
                        at org.springframework.orm.jpa.AbstractEntityManagerF actoryBean.afterPropertiesSet(AbstractEntityManage rFactoryBean.java:273)
                        at org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.invokeInitMethods(Abstr actAutowireCapableBeanFactory.java:1367)
                        at org.springframework.beans.factory.support.Abstract AutowireCapableBeanFactory.initializeBean(Abstract AutowireCapableBeanFactory.java:1333)
                        ... 47 more
                        Caused by: org.hibernate.MappingException: Could not determine type for: truefalse-type, at table: order, for columns: [org.hibernate.mapping.Column(is_latest)]
                        at org.hibernate.mapping.SimpleValue.getType(SimpleVa lue.java:292)
                        at org.hibernate.mapping.SimpleValue.isValid(SimpleVa lue.java:276)
                        at org.hibernate.mapping.Property.isValid(Property.ja va:207)
                        at org.hibernate.mapping.PersistentClass.validate(Per sistentClass.java:458)
                        at org.hibernate.mapping.RootClass.validate(RootClass .java:215)
                        at org.hibernate.cfg.Configuration.validate(Configura tion.java:1135)
                        at org.hibernate.cfg.Configuration.buildSessionFactor y(Configuration.java:1320)
                        at org.hibernate.cfg.AnnotationConfiguration.buildSes sionFactory(AnnotationConfiguration.java:867)
                        at org.hibernate.ejb.Ejb3Configuration.buildEntityMan agerFactory(Ejb3Configuration.java:669)
                        ... 53 more

                        Comment

                        Working...
                        X