Search Results

Search found 3046 results on 122 pages for 'hibernate validator'.

Page 5/122 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Variable length Blob in hibernate?

    - by Seth
    I have a byte[] member in one of my persistable classes. Normally, I'd just annotate it with @Lob and @Column(name="foo", size=). In this particular case, however, the length of the byte[] can vary a lot (from ~10KB all the way up to ~100MB). If I annotate the column with a size of 128MB, I feel like I'll be wasting a lot of space for the small and mid-sized objects. Is there a variable length blob type I can use? Will hibernate take care of all of this for me behind the scenes without wasting space? What's the best way to go about this? Thanks!

    Read the article

  • derby + hibernate ConstraintViolationException using manytomany relationships

    - by user364470
    Hi, I'm new to Hibernate+Derby... I've seen this issue mentioned throughout the google, but have not seen a proper resolution. This following code works fine with mysql, but when I try this on derby i get exceptions: ( each Tag has two sets of files and vise-versa - manytomany) Tags.java @Entity @Table(name="TAGS") public class Tags implements Serializable { @Id @GeneratedValue(strategy=GenerationType.AUTO) public long getId() { return id; } @ManyToMany(targetEntity=Files.class ) @ForeignKey(name="USER_TAGS_FILES",inverseName="USER_FILES_TAGS") @JoinTable(name="USERTAGS_FILES", joinColumns=@JoinColumn(name="TAGS_ID"), inverseJoinColumns=@JoinColumn(name="FILES_ID")) public Set<data.Files> getUserFiles() { return userFiles; } @ManyToMany(mappedBy="autoTags", targetEntity=data.Files.class) public Set<data.Files> getAutoFiles() { return autoFiles; } Files.java @Entity @Table(name="FILES") public class Files implements Serializable { @Id @GeneratedValue(strategy=GenerationType.AUTO) public long getId() { return id; } @ManyToMany(mappedBy="userFiles", targetEntity=data.Tags.class) public Set getUserTags() { return userTags; } @ManyToMany(targetEntity=Tags.class ) @ForeignKey(name="AUTO_FILES_TAGS",inverseName="AUTO_TAGS_FILES") @JoinTable(name="AUTOTAGS_FILES", joinColumns=@JoinColumn(name="FILES_ID"), inverseJoinColumns=@JoinColumn(name="TAGS_ID")) public Set getAutoTags() { return autoTags; } I add some data to the DB, but when running over Derby these exception turn up (the don't using mysql) Exceptions SEVERE: DELETE on table 'FILES' caused a violation of foreign key constraint 'USER_FILES_TAGS' for key (3). The statement has been rolled back. Jun 10, 2010 9:49:52 AM org.hibernate.event.def.AbstractFlushingEventListener performExecutions SEVERE: Could not synchronize database state with session org.hibernate.exception.ConstraintViolationException: could not delete: [data.Files#3] at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:96) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66) at org.hibernate.persister.entity.AbstractEntityPersister.delete(AbstractEntityPersister.java:2712) at org.hibernate.persister.entity.AbstractEntityPersister.delete(AbstractEntityPersister.java:2895) at org.hibernate.action.EntityDeleteAction.execute(EntityDeleteAction.java:97) at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:268) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:260) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:184) at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321) at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51) at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1206) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:613) at org.hibernate.context.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:344) at $Proxy13.flush(Unknown Source) at data.HibernateORM.removeFile(HibernateORM.java:285) at data.DataImp.removeFile(DataImp.java:195) at booting.DemoBootForTestUntilTestClassesExist.main(DemoBootForTestUntilTestClassesExist.java:62) I have never used derby before so maybe there is something crutal that i'm missing 1) what am I doing wrong? 2) is there any way of cascading properly when I have 2 many-to-many relationships between two classes? Thanks!

    Read the article

  • hibernate not picking sessionFactory

    - by Satya
    My application-context.xml is <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName"><value>com.mysql.jdbc.Driver</value></property> <property name="url"><value>jdbc:mysql://localhost:3306/myDB</value></property> <property name="username"><value>myUser</value></property> <property name="password"><value>myUser</value></property> </bean> <bean id="mySessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="mappingResources"> <property name="dataSource"><ref bean="myDataSource"/></property> <list> <value>com/x/model/config/hibernate/user.hbm.xml</value> </list> </property> <property name="hibernateProperties" > <value> hibernate.dialect=org.hibernate.dialect.MySQLDialect </value> </property> </bean> <bean id="userdao" class="com.x.y.z.UserDao"> <property name="sessionFactory"><ref bean="mySessionFactory"/></property> </bean> </beans> user.hbm.xml is <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.cpt.model"> <class name="User" table="user"> <id name="userId" column="id"> <generator class="native"/> </id> <property name="firstname" column="firstName" /> <property name="lastName" column="lastName"/> <property name="login" column="login"/> <property name="pass" column="pass"/> <property name="superemail" column="superEmail"/> </class> </hibernate-mapping> and the UserDao is package com.x.y.z; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.orm.hibernate.support.HibernateDaoSupport; import org.springframework.stereotype.Component; import com.x.model.User; @Component public class UserDao { private SessionFactory sessionFactory; public void addUser(User user) { Session session; try { try { session = getSessionFactory().openSession(); // session = sessionFactory.openSession(); session.save(user); } catch (RuntimeException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (HibernateException e) { // TODO Auto-generated catch block System.out.println("printing in the catch"); e.printStackTrace(); } } public SessionFactory getSessionFactory() { System.out.println("returning session factory ::: sessionFactory == null :: "+sessionFactory.openSession()); return sessionFactory; } public void setSessionFactory(SessionFactory sessionFactory) { System.out.println("this is setting session factory" + sessionFactory.getClass()); System.out.println("setting session factory ::: sessionFactory == null :: "+sessionFactory==null); this.sessionFactory = sessionFactory; System.out.println("setting session factory ::: sessionFactory == null :: "+this.sessionFactory.openSession().getClass()); System.out.println(getSessionFactory().openSession().isOpen()); } } However, I keep getting 14:45:09,929 INFO [org.hibernate.impl.SessionFactoryImpl] building session fact ory 14:45:09,933 WARN [net.sf.ehcache.config.Configurator] No configuration found. Configuring ehcache from ehcache-failsafe.xml found in the classpath: vfs:/C:/jb /server/default/deploy/C.war/WEB-INF/lib/ehcache-1.1.jar/ehcache-failsafe.xml 14:45:10,007 INFO [org.hibernate.impl.SessionFactoryObjectFactory] Not binding factory to JNDI, no JNDI name configured 14:45:10,008 INFO [org.hibernate.impl.SessionFactoryImpl] Checking 0 named quer ies 14:45:10,017 INFO [STDOUT] this is setting session factoryclass $Proxy178 14:45:10,017 INFO [STDOUT] false 14:45:10,019 INFO [STDOUT] setting session factory ::: sessionFactory == null : : class org.hibernate.impl.SessionImpl 14:45:10,020 INFO [STDOUT] returning session factory ::: sessionFactory == null :: org.hibernate.impl.SessionImpl(PersistentContext[entitiesByKey={}] ActionQue ue[insertions=[] updates=[] deletions=[] collectionCreations=[] collectionRemova ls=[] collectionUpdates=[]]) It is giving sessionFactory null . Any Idea where am I failing ? Thanks

    Read the article

  • JPA hibernate OneToOne mapping

    - by Stupidfrog
    enviroment: hibernate 4.1.6.final spring 3.1.2.release spring jpa 1.1.0.release postgresql 9.1-901-1.jdbc4 there is 2 table public A { private Long id; private Long name; } public B { private Long id; private Long table_a_id; } the A.id and B.id is sequential, unique , but no related.(means they are separately id for their own table). how to do mapping? i have tried some method, however the result is not i wanted, because it bind wrong. for example: public A { .... @OneToOne @JoinColumn(name = "id") private B table_b } public B { ... @JsonIgnore @OneToOne(mappedBy = "table_b") private A table_a; } when i query A the result is { "id":5, "table_b":{ "id":5, "table_a_id":4 } } obviously the data join by using their id but not joining using table_a_id. what i expect is { "id":4, "table_b":{ "id":5, "table_a_id":4 } } so can somebody teach me that, how to map this 2 table by using table b table_a_id(foregin key)

    Read the article

  • Spring-hibernate mapping problem

    - by James
    I have a spring-hibernate application which is failing to map an object properly: basically I have 2 domain objects, a Post and a User. The semantics are that every Post has 1 corresponding User. The Post domain object looks roughly as follows: class Post { private int pId; private String attribute; ... private User user; //getters and setters here } As you can see, Post contains a reference to User. When I load a Post object, I want to corresponding User object to be loaded (lazily - only when its needed). My mapping looks as follows: <class name="com...Post" table="post"> <id name="pId" column="PostId" /> <property name="attribute" column="Attribute" type="java.lang.String" /> <one-to-one name="User" fetch="join" class="com...User"></one-to-one> </class> And of course I have a basic mapping for User set up. As far as my table schema is concerned, I have a table called post with a foreign UserId which links to the user table. I thought this setup should work, BUT when I load a page that forces the lazy loading of the User object, I notice the following Hiberate query being generated: Select ... from post this_ left outer join user user2_ on this.PostId=user2_.UserId ... Obviously this is wrong: it should be joining UserId from post with UserId from user, but instead its incorrectly joining PostId from post (its primary key) with UserId from user. Any ideas? Thanks!

    Read the article

  • Mapping Hashmap of Coordinates in Hibernate with Annotation

    - by paddydub
    I've just started using hibernate and I'm trying to map walking distance between two coordinates into a hashmap, There can be many connections from one "FromCoordinate" to another "ToCoordinate". I'm not sure if i've implemented this correctly, What annotations do i need to map this MashMap? Thanks HashMap coordWalkingConnections = new HashMap(); @Entity @Table(name = "COORDCONNECTIONS") public class CoordinateConnection implements Serializable{ private static final long serialVersionUID = -1624745319005591573L; /** auto increasing id number */ @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "ID") @id private int id; @Embedded public FromCoordinate fromCoord; @Embedded public ToCoordinate toCoord; HashMap<FromCoordinate, ArrayList<ToCoordinate >> coordWalkingConnections = new HashMap<FromCoordinate, ArrayList<ToCoordinate >>(); } public class FromCoordinate implements ICoordinate { @Column(name = "FROM_LAT") private double latitude; @Column(name = "FROM_LNG") private double longitude; } public class ToCoordinate implements ICoordinate { @Column(name = "TO_LAT") private double latitude; @Column(name = "TO_LNG") private double longitude; @Column(name = "DISTANCE") private double distance; } DATABASE STRUCTURE id FROM_LAT FROM_LNG TO_LAT TO_LNG Dist 1 43.352669 -6.264341 43.350012 -6.260653 0.38 2 43.352669 -6.264341 43.352669 -6.264341 0.00 3 46.352669 -6.264341 43.353373 -6.262013 0.17 4 47.352465 -6.265865 43.351290 -6.261200 0.25 5 45.452578 -6.265768 43.352788 -6.264396 0.01 6 45.452578 -6.265768 45.782788 -6.234523 0.01 ..... ... . Example HashMap for HashMap<Coordinate, ArrayList<Coordinate>> <KEY{43.352669 -6.264341}, Arraylist VALUES{(43.350012,-6.260653,0.383657), (43.352669, -6.264341, 0.000095), (43.353373, -6.262013, 0.173201)}> <KEY{47.352465 -6.265865}, Arraylist VALUES{(43.351290,-6.261200,0.258781)}> <KEY{45.452578 -6.265768}, Arraylist VALUES{(43.352788,-6.264396,0.013726),(45.782788,-6.234523,0.017726)}>

    Read the article

  • Hibernate Mapping Annotation Question?

    - by paddydub
    I've just started using hibernate and I'm trying to map walking distance between two coordinates into a hashmap, There can be many connections from one "FromCoordinate" to another "ToCoordinate". I'm not sure if i've implemented this correctly, What annotations do i need to map this MashMap? Thanks @Entity @Table(name = "COORDCONNECTIONS") public class CoordinateConnection implements Serializable{ private static final long serialVersionUID = -1624745319005591573L; /** auto increasing id number */ @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "ID") @id private int id; @Embedded public FromCoordinate fromCoord; @Embedded public ToCoordinate toCoord; HashMap<Coordinate, ArrayList<Coordinate>> coordWalkingConnections = new HashMap<Coordinate, ArrayList<Coordinate>>(); } public class FromCoordinate implements ICoordinate { @Column(name = "FROM_LAT") private double latitude; @Column(name = "FROM_LNG") private double longitude; } public class ToCoordinate implements ICoordinate { @Column(name = "TO_LAT") private double latitude; @Column(name = "TO_LNG") private double longitude; @Column(name = "DISTANCE") private double distance; } DATABASE STRUCTURE id FROM_LAT FROM_LNG TO_LAT TO_LNG Dist 1 43.352669 -6.264341 43.350012 -6.260653 0.38 2 43.352669 -6.264341 43.352669 -6.264341 0.00 3 46.352669 -6.264341 43.353373 -6.262013 0.17 4 47.352465 -6.265865 43.351290 -6.261200 0.25 5 45.452578 -6.265768 43.352788 -6.264396 0.01 6 45.452578 -6.265768 45.782788 -6.234523 0.01 ..... ... . Example HashMap for HashMap<Coordinate, ArrayList<Coordinate>> <KEY{43.352669 -6.264341}, Arraylist VALUES{(43.350012,-6.260653,0.383657), (43.352669, -6.264341, 0.000095), (43.353373, -6.262013, 0.173201)}> <KEY{47.352465 -6.265865}, Arraylist VALUES{(43.351290,-6.261200,0.258781)}> <KEY{45.452578 -6.265768}, Arraylist VALUES{(43.352788,-6.264396,0.013726),(45.782788,-6.234523,0.017726)}>

    Read the article

  • Java Hibernate/C3P0 error: "Could not obtain connection metadata. An attempt by a client to checkout

    - by Allan
    I'm trying to get some code I was passed up and running. It appears to use the Hibernate framework. I've gotten past most of the errors tweaking the configuration, but this one has me dead stumped. It's trying to connect to two databases: gameapp and gamelog. Both exist. It seems to have issues connecting to gamelog, but none connecting to gameapp (later in the init, it connects to and loads other DBs just fine). Below, I've pasted the error and exception stack dump. I imaging there's something else in the configs, so I've also included the configuration file for that db. I know this is very vague, but I'm hoping some pro can see the stupid mistake I'm missing. <?xml version="1.0" encoding="GBK"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://127.0.0.1:3306/gamelog</property> <property name="connection.username">root</property> <property name="connection.password"></property> <property name="connection.useUnicode">true</property> <property name="connection.characterEncoding">UTF-8</property> <property name="hibernate.jdbc.batch_size">100</property> <property name="jdbc.fetch_size">1</property> <property name="hbm2ddl.auto">none</property><!-- update --> <property name="connection.useUnicode">true</property> <property name="show_sql">true</property> <!-- c3p0-configuration --> <property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property> <property name="hibernate.c3p0.min_size">5</property> <property name="hibernate.c3p0.max_size">10</property> <property name="hibernate.c3p0.timeout">30</property> <property name="hibernate.c3p0.idle_test_period">30</property> <property name="hibernate.c3p0.max_statements">0</property> <property name="hibernate.c3p0.acquire_increment">5</property> </session-factory> </hibernate-configuration> Exception and stack trace: 2010-04-30 17:50:00,411 WARN [org.hibernate.cfg.SettingsFactory] - Could not obtain connection metadata java.sql.SQLException: An attempt by a client to checkout a Connection has timed out. at com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:106) at com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:65) at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:527) at com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource.getConnection(AbstractPoolBackedDataSource.java:128) at org.hibernate.connection.C3P0ConnectionProvider.getConnection(C3P0ConnectionProvider.java:35) at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:76) at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:1933) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1216) at com.database.hibernate.util.HibernateFactory.<init>(Unknown Source) at com.database.hibernate.util.HibernateUtil.<clinit>(Unknown Source) at com.server.databaseop.goodOp.GoodOpImpl.initBreedGoods(Unknown Source) at com.server.databaseop.goodOp.GoodOpImpl.access$000(Unknown Source) at com.server.databaseop.goodOp.GoodOpImpl$1.run(Unknown Source) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) at java.util.concurrent.FutureTask$Sync.innerRunAndReset(FutureTask.java:351) at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:178) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:165) at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:267) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) at java.lang.Thread.run(Thread.java:636) Caused by: com.mchange.v2.resourcepool.TimeoutException: A client timed out while waiting to acquire a resource from com.mchange.v2.resourcepool.BasicResourcePool@ca470 -- timeout at awaitAvailable() at com.mchange.v2.resourcepool.BasicResourcePool.awaitAvailable(BasicResourcePool.java:1317) at com.mchange.v2.resourcepool.BasicResourcePool.prelimCheckoutResource(BasicResourcePool.java:557) at com.mchange.v2.resourcepool.BasicResourcePool.checkoutResource(BasicResourcePool.java:477) at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:525) ... 18 more

    Read the article

  • Joining tables with composite keys in a legacy system in hibernate

    - by Steve N
    Hi, I'm currently trying to create a pair of Hibernate annotated classes to load (read only) from a pair of tables in a legacy system. The legacy system uses a consistent (if somewhat dated) approach to keying tables. The tables I'm attempting to map are as follows: Customer CustomerAddress -------------------------- ---------------------------- customerNumber:string (pk) customerNumber:string (pk_1) name:string sequenceNumber:int (pk_2) street:string postalCode:string I've approached this by creating a CustomerAddress class like this: @Entity @Table(name="CustomerAddress") @IdClass(CustomerAddressKey.class) public class CustomerAddress { @Id @AttributeOverrides({ @AttributeOverride(name = "customerNumber", column = @Column(name="customerNumber")), @AttributeOverride(name = "sequenceNumber", column = @Column(name="sequenceNumber")) }) private String customerNumber; private int sequenceNumber; private String name; private String postalCode; ... } Where the CustomerAddressKey class is a simple Serializable object with the two key fields. The Customer object is then defined as: @Entity @Table(name = "Customer") public class Customer { private String customerNumber; private List<CustomerAddress> addresses = new ArrayList<CustomerAddress>(); private String name; ... } So, my question is: how do I express the OneToMany relationship on the Customer table?

    Read the article

  • W3c Markup Validator on Windows 2003 with Apache

    - by rihatum
    Hi All, OS = Windows 2003 (latest sp / hotfixes etc) Perl = Active Perl 5.8.9 Build 825 Apache 2.2.11 Followed the following How-To: http://validator.w3.org/docs/install_win.html Facing the following errors : (had an html error too, but I used Perl Package manager to upgrade the required package. Now, the Package manager isn't showing any update of the following package and some others too : SGML::Parser::OpenSP version 0.991 required--this is only version 0.99 at C:/www/validator/httpd/cgi-bin/check line 61. Q : How can I download the latest package for OpenSP ? Q : Would It be just a matter of click and install the package? If someone can provide a step by step that would be very helpful, I am not fluent with building perl packages. Thanks and Regards

    Read the article

  • Multiple database with Spring+Hibernate+JPA

    - by ziftech
    Hi everybody! I'm trying to configure Spring+Hibernate+JPA for work with two databases (MySQL and MSSQL) my datasource-context.xml: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"> <!-- Data Source config --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" p:driverClassName="${local.jdbc.driver}" p:url="${local.jdbc.url}" p:username="${local.jdbc.username}" p:password="${local.jdbc.password}"> </bean> <bean id="dataSourceRemote" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" p:driverClassName="${remote.jdbc.driver}" p:url="${remote.jdbc.url}" p:username="${remote.jdbc.username}" p:password="${remote.jdbc.password}" /> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" p:entity-manager-factory-ref="entityManagerFactory" /> <!-- JPA config --> <tx:annotation-driven transaction-manager="transactionManager" /> <bean id="persistenceUnitManager" class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager"> <property name="persistenceXmlLocations"> <list value-type="java.lang.String"> <value>classpath*:config/persistence.local.xml</value> <value>classpath*:config/persistence.remote.xml</value> </list> </property> <property name="dataSources"> <map> <entry key="localDataSource" value-ref="dataSource" /> <entry key="remoteDataSource" value-ref="dataSourceRemote" /> </map> </property> <property name="defaultDataSource" ref="dataSource" /> </bean> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="jpaVendorAdapter"> <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" p:showSql="true" p:generateDdl="true"> </bean> </property> <property name="persistenceUnitManager" ref="persistenceUnitManager" /> <property name="persistenceUnitName" value="localjpa"/> </bean> <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" /> </beans> each persistence.xml contains one unit, like this: <persistence-unit name="remote" transaction-type="RESOURCE_LOCAL"> <properties> <property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.DefaultNamingStrategy" /> <property name="hibernate.dialect" value="${remote.hibernate.dialect}" /> <property name="hibernate.hbm2ddl.auto" value="${remote.hibernate.hbm2ddl.auto}" /> </properties> </persistence-unit> PersistenceUnitManager cause following exception: Cannot resolve reference to bean 'persistenceUnitManager' while setting bean property 'persistenceUnitManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'persistenceUnitManager' defined in class path resource [config/datasource-context.xml]: Initialization of bean failed; nested exception is org.springframework.beans.TypeMismatchException: Failed to convert property value of type [java.util.ArrayList] to required type [java.lang.String] for property 'persistenceXmlLocation'; nested exception is java.lang.IllegalArgumentException: Cannot convert value of type [java.util.ArrayList] to required type [java.lang.String] for property 'persistenceXmlLocation': no matching editors or conversion strategy found If left only one persistence.xml without list, every works fine but I need 2 units... I also try to find alternative solution for work with two databases in Spring+Hibernate context, so I would appreciate any solution new error after changing to persistenceXmlLocations No single default persistence unit defined in {classpath:config/persistence.local.xml, classpath:config/persistence.remote.xml} UPDATE: I add persistenceUnitName, it works, but only with one unit, still need help UPDATE: thanks, ChssPly76 I changed config files: datasource-context.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" p:driverClassName="${local.jdbc.driver}" p:url="${local.jdbc.url}" p:username="${local.jdbc.username}" p:password="${local.jdbc.password}"> </bean> <bean id="dataSourceRemote" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" p:driverClassName="${remote.jdbc.driver}" p:url="${remote.jdbc.url}" p:username="${remote.jdbc.username}" p:password="${remote.jdbc.password}"> </bean> <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"> <property name="defaultPersistenceUnitName" value="pu1" /> </bean> <bean id="persistenceUnitManager" class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager"> <property name="persistenceXmlLocation" value="${persistence.xml.location}" /> <property name="defaultDataSource" ref="dataSource" /> <!-- problem --> <property name="dataSources"> <map> <entry key="local" value-ref="dataSource" /> <entry key="remote" value-ref="dataSourceRemote" /> </map> </property> </bean> <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="jpaVendorAdapter"> <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" p:showSql="true" p:generateDdl="true"> </bean> </property> <property name="persistenceUnitManager" ref="persistenceUnitManager" /> <property name="persistenceUnitName" value="pu1" /> <property name="dataSource" ref="dataSource" /> </bean> <bean id="entityManagerFactoryRemote" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="jpaVendorAdapter"> <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" p:showSql="true" p:generateDdl="true"> </bean> </property> <property name="persistenceUnitManager" ref="persistenceUnitManager" /> <property name="persistenceUnitName" value="pu2" /> <property name="dataSource" ref="dataSourceRemote" /> </bean> <tx:annotation-driven /> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" p:entity-manager-factory-ref="entityManagerFactory" /> <bean id="transactionManagerRemote" class="org.springframework.orm.jpa.JpaTransactionManager" p:entity-manager-factory-ref="entityManagerFactoryRemote" /> </beans> persistence.xml <?xml version="1.0" encoding="UTF-8"?> <persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0"> <persistence-unit name="pu1" transaction-type="RESOURCE_LOCAL"> <properties> <property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.DefaultNamingStrategy" /> <property name="hibernate.dialect" value="${local.hibernate.dialect}" /> <property name="hibernate.hbm2ddl.auto" value="${local.hibernate.hbm2ddl.auto}" /> </properties> </persistence-unit> <persistence-unit name="pu2" transaction-type="RESOURCE_LOCAL"> <properties> <property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.DefaultNamingStrategy" /> <property name="hibernate.dialect" value="${remote.hibernate.dialect}" /> <property name="hibernate.hbm2ddl.auto" value="${remote.hibernate.hbm2ddl.auto}" /> </properties> </persistence-unit> </persistence> Now it builds two entityManagerFactory, but both are for Microsoft SQL Server [main] INFO org.hibernate.ejb.Ejb3Configuration - Processing PersistenceUnitInfo [ name: pu1 ...] [main] INFO org.hibernate.cfg.SettingsFactory - RDBMS: Microsoft SQL Server [main] INFO org.hibernate.ejb.Ejb3Configuration - Processing PersistenceUnitInfo [ name: pu2 ...] [main] INFO org.hibernate.cfg.SettingsFactory - RDBMS: Microsoft SQL Server (but must MySQL) I suggest, that use only dataSource, dataSourceRemote (no substitution) is not worked. That's my last problem

    Read the article

  • Having an issue with org.hibernate.SessionException: Session is closed! in Hibernate

    - by hal10001
    I've done quite a bit a research on this with no luck, but all the answers have a tendency to point toward the session context settings in the config file. What is odd is that I get a session connection the very first time I hit the page (and therefore, a successful result set), but then when I reload I get the following exception: org.hibernate.SessionException: Session is closed! Here are my config settings that are not DB connection string related: <property name="hibernate.show_sql">false</property> <property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property> <property name="hibernate.current_session_context_class">thread</property> <property name="hibernate.cache.provider_class">org.hibernate.cache.NoCacheProvider</property> <property name="hibernate.cache.use_query_cache">false</property> <property name="hibernate.cache.use_minimal_puts">false</property> Here is an example of a call I make that produces the situation I described above. public T get(int id) { session.beginTransaction(); T type; try { type = getTypeClass().cast(session.get(getTypeClass(), id)); } catch (ClassCastException classCastException) { throw new ClassCastException(classCastException.getMessage()); } session.getTransaction().commit(); return type; } The session variable reference is to a static field that contains the current session. All of the session connection details are textbook reference manual. For example, here is my Hibernate session utility: import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateSessionFactoryUtil { private static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() { try { return new Configuration().configure().buildSessionFactory(); } catch (Throwable ex) { System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } }

    Read the article

  • hibernate c3p0 broken pipe

    - by raven_arkadon
    Hi, I'm using hibernate 3 with c3p0 for a program which constantly extracts data from some source and writes it to a database. Now the problem is, that the database might become unavailable for some reasons (in the simplest case: i simply shut it down). If anything is about to be written to the database there should not be any exception - the query should wait for all eternity until the database becomes available again. If I'm not mistaken this is one of the things the connection pool could do for me: if there is a problem with the db, just retry to connect - in the worst case for infinity. But instead i get a broken pipe exception, sometimes followed by connection refused and then the exception is passed to my own code, which shouldn't happen. Even if I catch the exception, how could i cleanly reinitialize hibernate again? (So far without c3p0 i simply built the session factory again, but i wouldn't be surprised if that could leak connections (or is it ok to do so?)). The database is Virtuoso open source edition. My hibernate.xml.cfg c3p0 config: <property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property> <property name="hibernate.c3p0.breakAfterAcquireFailure">false</property> <property name="hibernate.c3p0.acquireRetryAttempts">-1</property> <property name="hibernate.c3p0.acquireRetryDelay">30000</property> <property name="hibernate.c3p0.automaticTestTable">my_test_table</property> <property name="hibernate.c3p0.initialPoolSize">3</property> <property name="hibernate.c3p0.minPoolSize">3</property> <property name="hibernate.c3p0.maxPoolSize">10</property> btw: The test table is created and i get tons of debug output- so it seems it actually reads the config.

    Read the article

  • What are the advantages of myBatis over Hibernate?

    - by Kshitiz Sharma
    This question originates from a comment I received on one of my questions - I'd rather drop hibernate in favor of mybatis instead of jdbc I've done some research on my own and understand the basic concept. But some insights can only be gained through actual experience. What are the advantages of myBatis that would make it worth learning a new framework? In what case would you avoid using it?

    Read the article

  • How can I map "insert='false' update='false'" on a composite-id key-property which is also used in a one-to-many FK?

    - by Gweebz
    I am working on a legacy code base with an existing DB schema. The existing code uses SQL and PL/SQL to execute queries on the DB. We have been tasked with making a small part of the project database-engine agnostic (at first, change everything eventually). We have chosen to use Hibernate 3.3.2.GA and "*.hbm.xml" mapping files (as opposed to annotations). Unfortunately, it is not feasible to change the existing schema because we cannot regress any legacy features. The problem I am encountering is when I am trying to map a uni-directional, one-to-many relationship where the FK is also part of a composite PK. Here are the classes and mapping file... CompanyEntity.java public class CompanyEntity { private Integer id; private Set<CompanyNameEntity> names; ... } CompanyNameEntity.java public class CompanyNameEntity implements Serializable { private Integer id; private String languageId; private String name; ... } CompanyNameEntity.hbm.xml <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.jboss.org/dtd/hibernate/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.example"> <class name="com.example.CompanyEntity" table="COMPANY"> <id name="id" column="COMPANY_ID"/> <set name="names" table="COMPANY_NAME" cascade="all-delete-orphan" fetch="join" batch-size="1" lazy="false"> <key column="COMPANY_ID"/> <one-to-many entity-name="vendorName"/> </set> </class> <class entity-name="companyName" name="com.example.CompanyNameEntity" table="COMPANY_NAME"> <composite-id> <key-property name="id" column="COMPANY_ID"/> <key-property name="languageId" column="LANGUAGE_ID"/> </composite-id> <property name="name" column="NAME" length="255"/> </class> </hibernate-mapping> This code works just fine for SELECT and INSERT of a Company with names. I encountered a problem when I tried to update and existing record. I received a BatchUpdateException and after looking through the SQL logs I saw Hibernate was trying to do something stupid... update COMPANY_NAME set COMPANY_ID=null where COMPANY_ID=? Hibernate was trying to dis-associate child records before updating them. The problem is that this field is part of the PK and not-nullable. I found the quick solution to make Hibernate not do this is to add "not-null='true'" to the "key" element in the parent mapping. SO now may mapping looks like this... CompanyNameEntity.hbm.xml <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.jboss.org/dtd/hibernate/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.example"> <class name="com.example.CompanyEntity" table="COMPANY"> <id name="id" column="COMPANY_ID"/> <set name="names" table="COMPANY_NAME" cascade="all-delete-orphan" fetch="join" batch-size="1" lazy="false"> <key column="COMPANY_ID" not-null="true"/> <one-to-many entity-name="vendorName"/> </set> </class> <class entity-name="companyName" name="com.example.CompanyNameEntity" table="COMPANY_NAME"> <composite-id> <key-property name="id" column="COMPANY_ID"/> <key-property name="languageId" column="LANGUAGE_ID"/> </composite-id> <property name="name" column="NAME" length="255"/> </class> </hibernate-mapping> This mapping gives the exception... org.hibernate.MappingException: Repeated column in mapping for entity: companyName column: COMPANY_ID (should be mapped with insert="false" update="false") My problem now is that I have tryed to add these attributes to the key-property element but that is not supported by the DTD. I have also tryed changing it to a key-many-to-one element but that didn't work either. So... How can I map "insert='false' update='false'" on a composite-id key-property which is also used in a one-to-many FK?

    Read the article

  • Hibernate without primary keys generated by db?

    - by Michael Jones
    I'm building a data warehouse and want to use InfiniDB as the storage engine. However, it doesn't allow primary keys or foreign key constraints (or any constraints for that matter). Hibernate complains "The database returned no natively generated identity value" when I perform an insert. Each table is relational, and contains a unique integer column that was previously used as the primary key - I want to keep that, but just not have the constraint in the db that the column is the primary key. I'm assuming the problem is that Hibernate expects the db to return a generated key. Is it possible to override this behaviour so I can set the primary key field's value myself and keep Hibernate happy? -- edit -- Two of the mappings are as follows: <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Generated Jun 1, 2010 2:49:51 PM by Hibernate Tools 3.2.1.GA --> <hibernate-mapping> <class name="com.example.project.Visitor" table="visitor" catalog="orwell"> <id name="id" type="java.lang.Long"> <column name="id" /> <generator class="identity" /> </id> <property name="firstSeen" type="timestamp"> <column name="first_seen" length="19" /> </property> <property name="lastSeen" type="timestamp"> <column name="last_seen" length="19" /> </property> <property name="sessionId" type="string"> <column name="session_id" length="26" unique="true" /> </property> <property name="userId" type="java.lang.Long"> <column name="user_id" /> </property> <set name="visits" inverse="true"> <key> <column name="visitor_id" /> </key> <one-to-many class="com.example.project.Visit" /> </set> </class> </hibernate-mapping> and: <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Generated Jun 1, 2010 2:49:51 PM by Hibernate Tools 3.2.1.GA --> <hibernate-mapping> <class name="com.example.project.Visit" table="visit" catalog="orwell"> <id name="id" type="java.lang.Long"> <column name="id" /> <generator class="identity" /> </id> <many-to-one name="visitor" class="com.example.project.Visitor" fetch="join" cascade="all"> <column name="visitor_id" /> </many-to-one> <property name="visitId" type="string"> <column name="visit_id" length="20" unique="true" /> </property> <property name="startTime" type="timestamp"> <column name="start_time" length="19" /> </property> <property name="endTime" type="timestamp"> <column name="end_time" length="19" /> </property> <property name="userAgent" type="string"> <column name="user_agent" length="65535" /> </property> <set name="pageViews" inverse="true"> <key> <column name="visit_id" /> </key> <one-to-many class="com.example.project.PageView" /> </set> </class> </hibernate-mapping>

    Read the article

  • Got back Hibernation option, but cannot resume from Hibernate

    - by harisibrahimkv
    In my Ubuntu 12.04, the hibernation option was working well and fine. However, I installed Debian on another partition recently and when I again tried to boot to Ubuntu, I got a message on the boot splash screen saying : The disk drive for / is not ready yet or not present. Continue to wait; or press s to skip mounting or M for manual recovery. After logging into Ubuntu, I find that my hibernation option has gone missing. Is there anyway to recover the hibernation option? EDIT: I solved the disk drive problem and I got the hibernation option back. When I did "sudo pm-hibernate", my system went to hibernation. However, when powering on again, it booted up normally and thus there was no effect of hibernation. How can this be rectified? EDIT1: System - Lenovo ideapad s10-2. EDIT2: /etc/fstab

    Read the article

  • Why were annotations introduced in Spring and Hibernate?

    - by Chandrashekhar
    I would like to know why were annotations introduced in Spring and Hibernate? For earlier versions of both the frameworks book authors were saying that if we keep configuration in xml files then it will be easier to maintain (due to decoupling) and just by changing the xml file we can re-configure the application. If we use annotations in our project and in future we want to re-configure application then again we have to compile and build the project. So why were these annotations introduced in these frameworks? From my point of view annotations make the apps dependent on certain framework. Isn't it true?

    Read the article

  • Computer won't wake from hibernate

    - by Icoo
    So I have a pretty dumb problem...I accidentaly pressed Hibernate while trying to Restart...since then my computer wont boot into Ubuntu anymore (through normal mode or single user mode - rescue mode that is)...all I get is: mount: mounting /dev on /root/dev failed: No such file or directory mount: mounting /sys/ on root/sys failed: No such file or directory mount: mounting /proc on /root/proc failed: No such file or dirctory Target filesystem doesn't have requested /sbin/init. No init found. Try passing init= boot arg. BusyBox v1.15.3 (Ubuntu 1:1.15.3-1ubuntu5) built-in shell (ash) Enter 'help' for a list of built-in commands. (initramfs) Obviously I tried to fire up the Live CD and run fsck (or e2fsck) from there (or just try to do a Check of /dev/sdb1 my partition via gparted - which is basically the same thing). But it doesn't allow me...both gparted and fsck say that the device is busy (I can't even mount it in the LiveCD to rescue data)...umount /dev/sdb1 says its not mounted...any ideas?

    Read the article

  • Hibernate many-to-many mapping not saved in pivot table

    - by vincent
    I having problems saving many to many relationships to a pivot table. The way the pojos are created is unfortunately a pretty long process which spans over a couple of different threads which work on the (to this point un-saved) object until it is finally persisted. I associate the related objects to one another right after they are created and when debugging I can see the List of related object populated with their respective objects. So basically all is fine to this point. When I persist the object everything get saved except the relations in the pivot table. mapping files: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.thebeansgroup.jwinston.plugin.orm.hibernate.object"> <class name="ShowObject" table="show_object"> <id name="id"> <generator class="native" /> </id> <property name="name" /> <set cascade="all" inverse="true" name="venues" table="venue_show"> <key column="show_id"/> <many-to-many class="VenueObject"/> </set> </class> </hibernate-mapping> and the other <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.thebeansgroup.jwinston.plugin.orm.hibernate.object"> <class name="VenueObject" table="venue_object"> <id name="id"> <generator class="native"/> </id> <property name="name"/> <property name="latitude" type="integer"/> <property name="longitude" type="integer"/> <set cascade="all" inverse="true" name="shows" table="venue_show"> <key column="venue_id"/> <many-to-many class="ShowObject"/> </set> </class> </hibernate-mapping> pojos: public class ShowObject extends OrmObject { private Long id; private String name; private Set venues; public ShowObject() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Set getVenues() { return venues; } public void setVenues(Set venues) { this.venues = venues; } } and the other: public class VenueObject extends OrmObject { private Long id; private String name; private int latitude; private int longitude; private Set shows = new HashSet(); public VenueObject() { } @Id @GeneratedValue(strategy = GenerationType.AUTO) public Long getId() { return id; } public void setId(Long id) { this.id = id; } public int getLatitude() { return latitude; } public void setLatitude(int latitude) { this.latitude = latitude; } public int getLongitude() { return longitude; } public void setLongitude(int longitude) { this.longitude = longitude; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Set getShows() { return shows; } public void setShows(Set shows) { this.shows = shows; } } Might the problem be related to the lack of annotations?

    Read the article

  • data is not inserting in my db table [closed]

    - by Sarojit Chakraborty
    Please see my below(SubjectDetailsDao.java) code of addZoneToDb method. My debugger is nicely running upto ** session.getTransaction().commit();** code. but after that debugger stops,I do not know why it stops after that line? .And because of this i am unable to insert my data into my database table. I don't know what to do.Why it is not inserting my data into my database table? Plz help me for this. H Now i am getting this Error: Struts Problem Report Struts has detected an unhandled exception: Messages: org.hibernate.event.PreInsertEvent.getSource()Lorg/hibernate/event/EventSource; File: org/hibernate/validator/event/ValidateEventListener.java Line number: 172 Stacktraces java.lang.reflect.InvocationTargetException sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) java.lang.reflect.Method.invoke(Method.java:601) com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:441) com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:280) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:243) com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:165) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:252) org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:179) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:94) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:235) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:89) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:130) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:126) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:138) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:165) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:179) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52) org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:488) org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77) org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91) org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243) org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240) org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164) org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:498) org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100) org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:562) org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:394) org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:243) org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:188) org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:302) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) java.lang.Thread.run(Thread.java:722) java.lang.NoSuchMethodError: org.hibernate.event.PreInsertEvent.getSource()Lorg/hibernate/event/EventSource; org.hibernate.validator.event.ValidateEventListener.onPreInsert(ValidateEventListener.java:172) org.hibernate.action.EntityInsertAction.preInsert(EntityInsertAction.java:156) org.hibernate.action.EntityInsertAction.execute(EntityInsertAction.java:49) org.hibernate.engine.ActionQueue.execute(ActionQueue.java:250) org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:234) org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:141) org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298) org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27) org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000) org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:338) org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106) v.esoft.dao.SubjectdetailsDAO.SubjectdetailsDAO.addZoneToDb(SubjectdetailsDAO.java:185) v.esoft.actions.LoginAction.datatobeinsert(LoginAction.java:53) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) java.lang.reflect.Method.invoke(Method.java:601) com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:441) com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:280) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:243) com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:165) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:252) org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68) ............................... ............................... SubjectDetailsDao.java(I have problem in addZoneToDb) package v.esoft.dao.SubjectdetailsDAO; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.criterion.Order; import com.opensymphony.xwork2.ActionSupport; import v.esoft.connection.HibernateUtil; import v.esoft.pojos.Subjectdetails; public class SubjectdetailsDAO extends ActionSupport { private static Session session = null; private static SessionFactory sessionFactory = null; static Transaction transaction = null; private String currentDate; SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd"); private java.util.Date currentdate; public SubjectdetailsDAO() { sessionFactory = HibernateUtil.getSessionFactory(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); currentdate = new java.util.Date(); currentDate = formatter.format(currentdate); } public List getAllCustomTempleteRoutinesForGrid() { List list = new ArrayList(); try { session = sessionFactory.openSession(); list = session.createCriteria(Subjectdetails.class).addOrder(Order.desc("subjectId")).list(); } catch (Exception e) { System.out.println("Exepetion in getAllCustomTempleteRoutines" + e); } finally { try { // HibernateUtil.shutdown(); } catch (Exception e) { System.out.println("Exception In getExerciseListByLoginId Resource closing :" + e); } } return list; } //**showing list on grid private static List<Subjectdetails> custLst=new ArrayList<Subjectdetails>(); static int total=50; static { SubjectdetailsDAO cts = new SubjectdetailsDAO(); Iterator iterator1 = cts.getAllCustomTempleteRoutinesForGrid().iterator(); while (iterator1.hasNext()) { Subjectdetails get = (Subjectdetails) iterator1.next(); custLst.add(get); } } /****************************************update Routines List by WorkId************************************/ public int updatesub(Subjectdetails s) { int updated = 0; try { session = sessionFactory.openSession(); transaction = session.beginTransaction(); Query query = session.createQuery("UPDATE Subjectdetails set subjectName = :routineName1 WHERE subjectId=:workoutId1"); query.setString("routineName1", s.getSubjectName()); query.setInteger("workoutId1", s.getSubjectId()); updated = query.executeUpdate(); if (updated != 0) { } transaction.commit(); } catch (Exception e) { if (transaction != null && transaction.isActive()) { try { transaction.rollback(); } catch (Exception e1) { System.out.println("Exception in addUser() Rollback :" + e1); } } } finally { try { session.flush(); session.close(); } catch (Exception e) { System.out.println("Exception In addUser Resource closing :" + e); } } return updated; } /****************************************update Routines List by WorkId************************************/ public int addSubjectt(Subjectdetails s) { int inserted = 0; Subjectdetails ss=new Subjectdetails(); try { session = sessionFactory.openSession(); transaction = session.beginTransaction(); ss. setSubjectName(s.getSubjectName()); session.save(ss); System.out.println("Successfully data insert in database"); inserted++; if (inserted != 0) { } transaction.commit(); } catch (Exception e) { if (transaction != null && transaction.isActive()) { try { transaction.rollback(); } catch (Exception e1) { System.out.println("Exception in addUser() Rollback :" + e1); } } } finally { try { session.flush(); session.close(); } catch (Exception e) { System.out.println("Exception In addUser Resource closing :" + e); } } return inserted; } /******************************************Get all Routines List by LoginID************************************/ public List getSubjects() { List list = null; try { session = sessionFactory.openSession(); list = session.createCriteria(Subjectdetails.class).list(); } catch (Exception e) { System.out.println("Exception in getRoutineList() :" + e); } finally { try { session.flush(); session.close(); } catch (Exception e) { System.out.println("Exception In getUserList Resource closing :" + e); } } return list; } //---\ public int addZoneToDb(String countryName, Integer loginId) { int inserted = 0; try { System.out.println("---------1--------"); Session session = HibernateUtil.getSessionFactory().openSession(); System.out.println("---------2------session--"+session); session.beginTransaction(); Subjectdetails country = new Subjectdetails(countryName, loginId, currentdate, loginId, currentdate); System.out.println("---------2------country--"+country); session.save(country); System.out.println("-------after save--"); inserted++; session.getTransaction().commit(); System.out.println("-------after commits--"); } catch (Exception e) { if (transaction != null && transaction.isActive()) { try { transaction.rollback(); } catch (Exception e1) { } } } finally { try { } catch (Exception e) { } } return inserted; } //-- public int nextId() { return total++; } public List<Subjectdetails> buildList() { return custLst; } public static int count() { return custLst.size(); } public static List<Subjectdetails> find(int o,int q) { return custLst.subList(o, q); } public void save(Subjectdetails c) { custLst.add(c); } public static Subjectdetails findById(Integer id) { try { for(Subjectdetails c:custLst) { if(c.getSubjectId()==id) { return c; } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } public void update(Subjectdetails c) { for(Subjectdetails x:custLst) { if(x.getSubjectId()==c.getSubjectId()) { x.setSubjectName(c.getSubjectName()); } } } public void delete(Subjectdetails c) { custLst.remove(c); } public static List<Subjectdetails> findNotById(int id, int from,int to) { List<Subjectdetails> subLst=custLst.subList(from, to); List<Subjectdetails> temp=new ArrayList<Subjectdetails>(); for(Subjectdetails c:subLst) { if(c.getSubjectId()!=id) { temp.add(c); } } return temp; } public static List<Subjectdetails> findLesserAsId(int id, int from,int to) { List<Subjectdetails> subLst=custLst.subList(from, to); List<Subjectdetails> temp=new ArrayList<Subjectdetails>(); for(Subjectdetails c:subLst) { if(c.getSubjectId()<=id) { temp.add(c); } } return temp; } public static List<Subjectdetails> findGreaterAsId(int id, int from,int to) { List<Subjectdetails> subLst=custLst.subList(from, to); List<Subjectdetails> temp=new ArrayList<Subjectdetails>(); for(Subjectdetails c:subLst) { if(c.getSubjectId()>=id) { temp.add(c); } } return temp; } } Subjectdetails.hbm.xml <hibernate-mapping> <class name="vb.sofware.pojos.Subjectdetails" table="subjectdetails" catalog="vbsoftware"> <id name="subjectId" type="int"> <column name="subject_id" /> <generator class="increment"/> </id> <property name="subjectName" type="string"> <column name="subject_name" length="150" /> </property> <property name="createrId" type="java.lang.Integer"> <column name="creater_id" /> </property> <property name="createdDate" type="timestamp"> <column name="created_date" length="19" /> </property> <property name="updateId" type="java.lang.Integer"> <column name="update_id" /> </property> <property name="updatedDate" type="timestamp"> <column name="updated_date" length="19" /> </property> </class> </hibernate-mapping> My POJO - Subjectdetails.java package v.esoft.pojos; // Generated Oct 6, 2012 1:58:21 PM by Hibernate Tools 3.4.0.CR1 import java.util.Date; /** * Subjectdetails generated by hbm2java */ public class Subjectdetails implements java.io.Serializable { private int subjectId; private String subjectName; private Integer createrId; private Date createdDate; private Integer updateId; private Date updatedDate; public Subjectdetails( String subjectName) { //this.subjectId = subjectId; this.subjectName = subjectName; } public Subjectdetails() { } public Subjectdetails(int subjectId) { this.subjectId = subjectId; } public Subjectdetails(int subjectId, String subjectName, Integer createrId, Date createdDate, Integer updateId, Date updatedDate) { this.subjectId = subjectId; this.subjectName = subjectName; this.createrId = createrId; this.createdDate = createdDate; this.updateId = updateId; this.updatedDate = updatedDate; } public Subjectdetails( String subjectName, Integer createrId, Date createdDate, Integer updateId, Date updatedDate) { this.subjectName = subjectName; this.createrId = createrId; this.createdDate = createdDate; this.updateId = updateId; this.updatedDate = updatedDate; } public int getSubjectId() { return this.subjectId; } public void setSubjectId(int subjectId) { this.subjectId = subjectId; } public String getSubjectName() { return this.subjectName; } public void setSubjectName(String subjectName) { this.subjectName = subjectName; } public Integer getCreaterId() { return this.createrId; } public void setCreaterId(Integer createrId) { this.createrId = createrId; } public Date getCreatedDate() { return this.createdDate; } public void setCreatedDate(Date createdDate) { this.createdDate = createdDate; } public Integer getUpdateId() { return this.updateId; } public void setUpdateId(Integer updateId) { this.updateId = updateId; } public Date getUpdatedDate() { return this.updatedDate; } public void setUpdatedDate(Date updatedDate) { this.updatedDate = updatedDate; } } And my Sql query is CREATE TABLE IF NOT EXISTS `subjectdetails` ( `subject_id` int(3) NOT NULL, `subject_name` varchar(150) DEFAULT NULL, `creater_id` int(5) DEFAULT NULL, `created_date` datetime DEFAULT NULL, `update_id` int(5) DEFAULT NULL, `updated_date` datetime DEFAULT NULL, PRIMARY KEY (`subject_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1;

    Read the article

  • JPA/Hibernate Embedded id

    - by RoD
    I would like to do something like that: An object ReportingFile that can be a LogRequest or a LogReport file. ( both got the same structure) An object Reporting containing for one logRequest, a list of logReport with a date. I tryed to set an EmbededId, that would be an attribute of the logRequest. And that's the problem i got. I don't arrive to mannage embedded id. ( http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/#entity-mapping-identifier ) If you have a clue on how i should do it :) An example (not working) would be: @Entity @AssociationOverride( name="logRequest.fileName", joinColumns = { @JoinColumn(name="log_request_file_name") } ) public class Reporting { @EmbeddedId private ReportingFile logRequest; @CollectionOfElements(fetch = FetchType.EAGER) @JoinTable(name = "t_reports", schema="", joinColumns = {@JoinColumn(name = "log_report")}) @Fetch(FetchMode.SELECT) private List<ReportingFile> reports; @Column(name="generated_date",nullable=true) private Date generatedDate; [...] } @Embeddable public class ReportingFile { @Column(name="file_name",length=255) private String fileName; @Column(name="xml_content") private Clob xmlContent; [...] } In this sample, i have a the following error: 15.03.2010 16:37:59 [ERROR] org.springframework.web.context.ContextLoader Context initialization failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor#0' defined in class path resource [config/persistenceContext.xml]: Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [config/persistenceContext.xml]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: test] Unable to configure EntityManagerFactory at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:480) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409) at java.security.AccessController.doPrivileged(Native Method) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:221) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164) at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:881) at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:597) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:366) at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:255) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:199) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:45) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3843) at org.apache.catalina.core.StandardContext.start(StandardContext.java:4350) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045) at org.apache.catalina.core.StandardHost.start(StandardHost.java:719) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045) at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443) at org.apache.catalina.core.StandardService.start(StandardService.java:516) at org.apache.catalina.core.StandardServer.start(StandardServer.java:710) at org.apache.catalina.startup.Catalina.start(Catalina.java:578) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413) Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [config/persistenceContext.xml]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: test] Unable to configure EntityManagerFactory at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1337) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:473) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409) at java.security.AccessController.doPrivileged(Native Method) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:221) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164) at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:308) at org.springframework.beans.factory.BeanFactoryUtils.beansOfTypeIncludingAncestors(BeanFactoryUtils.java:270) at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.detectPersistenceExceptionTranslators(PersistenceExceptionTranslationInterceptor.java:122) at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.<init>(PersistenceExceptionTranslationInterceptor.java:78) at org.springframework.dao.annotation.PersistenceExceptionTranslationAdvisor.<init>(PersistenceExceptionTranslationAdvisor.java:70) at org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor.setBeanFactory(PersistenceExceptionTranslationPostProcessor.java:97) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1325) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:473) ... 29 more Caused by: javax.persistence.PersistenceException: [PersistenceUnit: test] Unable to configure EntityManagerFactory at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:265) at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:125) at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:83) at org.springframework.orm.jpa.LocalEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalEntityManagerFactoryBean.java:91) at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:291) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1368) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1334) ... 46 more Caused by: org.hibernate.AnnotationException: A Foreign key refering Reporting from Reporting has the wrong number of column. should be 2 at org.hibernate.cfg.annotations.TableBinder.bindFk(TableBinder.java:272) at org.hibernate.cfg.annotations.CollectionBinder.bindCollectionSecondPass(CollectionBinder.java:1319) at org.hibernate.cfg.annotations.CollectionBinder.bindManyToManySecondPass(CollectionBinder.java:1158) at org.hibernate.cfg.annotations.CollectionBinder.bindStarToManySecondPass(CollectionBinder.java:600) at org.hibernate.cfg.annotations.CollectionBinder$1.secondPass(CollectionBinder.java:541) at org.hibernate.cfg.CollectionSecondPass.doSecondPass(CollectionSecondPass.java:43) at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1140) at org.hibernate.cfg.AnnotationConfiguration.secondPassCompile(AnnotationConfiguration.java:319) at org.hibernate.cfg.Configuration.buildMappings(Configuration.java:1125) at org.hibernate.ejb.Ejb3Configuration.buildMappings(Ejb3Configuration.java:1226) at org.hibernate.ejb.EventListenerConfigurator.configure(EventListenerConfigurator.java:159) at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:854) at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:191) at org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:253) ... 52 more

    Read the article

  • Hibernate mapping one-to-many problem

    - by Xorty
    Hello, I am not very experienced with Hibernate and I am trying to create one-to-many mapping. Here are relevant tables: And here are my mapping files: <hibernate-mapping package="com.xorty.mailclient.server.domain"> <class name="Attachment" table="Attachment"> <id name="id"> <column name="idAttachment"></column> </id> <property name="filename"> <column name="name"></column> </property> <property name="blob"> <column name="file"></column> <type name="blob"></type> </property> <property name="mailId"> <column name="mail_idmail"></column> </property> </class> </hibernate-mapping> <hibernate-mapping> <class name="com.xorty.mailclient.server.domain.Mail" table="mail"> <id name="id" type="integer" column="idmail"></id> <property name="content"> <column name="body"></column> </property> <property name="ownerAddress"> <column name="account_address"></column> </property> <property name="title"> <column name="head"></column> </property> <set name="receivers" table="mail_has_contact" cascade="all"> <key column="mail_idmail"></key> <many-to-many column="contact_address" class="com.xorty.mailclient.client.domain.Contact"></many-to-many> </set> <list name="attachments" cascade="save-update, delete" inverse="true"> <key column="mail_idmail" not-null="true"/> <index column="fk_Attachment_mail1"></index> <one-to-many class="com.xorty.mailclient.server.domain.Attachment"/> </list> </class> </hibernate-mapping> In plain english, one mail has more attachments. When I try to do CRUD on mail without attachments, everyting works just fine. When I add some attachment to mail, I cannot perform any CRUD operation. I end up with following trace: org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:96) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66) at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:275) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:268) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:184) at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321) at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51) at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1216) at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:383) at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:133) at domain.DatabaseTest.testPersistMailWithAttachment(DatabaseTest.java:355) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at junit.framework.TestCase.runTest(TestCase.java:168) at junit.framework.TestCase.runBare(TestCase.java:134) at junit.framework.TestResult$1.protect(TestResult.java:110) at junit.framework.TestResult.runProtected(TestResult.java:128) at junit.framework.TestResult.run(TestResult.java:113) at junit.framework.TestCase.run(TestCase.java:124) at junit.framework.TestSuite.runTest(TestSuite.java:232) at junit.framework.TestSuite.run(TestSuite.java:227) at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:83) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197) Caused by: java.sql.BatchUpdateException: Cannot add or update a child row: a foreign key constraint fails (`maildb`.`attachment`, CONSTRAINT `fk_Attachment_mail1` FOREIGN KEY (`mail_idmail`) REFERENCES `mail` (`idmail`) ON DELETE NO ACTION ON UPDATE NO ACTION) at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:1666) at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:1082) at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70) at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268) ... 27 more Thank you

    Read the article

  • Hibernate mapping, on a unmapped class

    - by Jan
    Hi, I' ve got 2 tables... Challenge and ChallengeYear, ChallengeYear is only to create a list of years in challenge. I only want to make Challenge an entity, containing a list of List years. Is this possible? I've looked in to @SecondaryTable together with @JoinColumn and @OneToMany, but neither of those can do the trick, or i am overlooking something. Can someone help me? Greetings, Jan

    Read the article

  • Hibernate-Search: How to search dates?

    - by Aaron
    @Entity @Table(name = "USERS") public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; @Column(name = "USERNAME", nullable = false, length = 20) private String userName; @Column(name = "PASSWORD", nullable = false, length = 10) private String password; @Column(name = "Date", nullable = false ) private Date date; } How can I select the records which have the date between [now | now-x hours] [now | now-x days] [now | now-x months] [now | now-x years]

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >