JPA: Override Auto generated ID [duplicate]

I wrote my own generator to solve the issue. public class UseExistingIdOtherwiseGenerateUsingIdentity extends IdentityGenerator { @Override public Serializable generate(SharedSessionContractImplementor session, Object object) throws HibernateException { Serializable id = session.getEntityPersister(null, object).getClassMetadata().getIdentifier(object, session); return id != null ? id : super.generate(session, object); } } and use it like this: (replace the package name) @Id @GenericGenerator(name = “UseExistingIdOtherwiseGenerateUsingIdentity”, … Read more

java.lang.ClassNotFoundException: javax.persistence.Persistence cannot be found with JPA

You are trying to set up a standalone JPA project. In order to do so you need a JPA provider jars. The two more popular providers are Eclipselink and Hibernate. If you are using maven you can add dependencies to their implementations. For Eclipselink <dependency> <groupId>org.eclipse.persistence</groupId> <artifactId>eclipselink</artifactId> <version>2.5.1</version> </dependency> For Hibernate <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>4.3.6.Final</version> … Read more

In Spring with jpa/hibernate, how do I keep a session open to avoid lazy initialization exceptions?

https://www.hibernate.org/43.html Basically, you have a few options. -You can use the “open session in view” pattern where you use a filter/interceptor/AOP – style logic to open a session when server side logic begins, and close it when it’s through. -You could implement conversations spanning several request-response cycles. A plain old Servlet Filter is the easiest.

Spring Data + JPA with multiple datasources but only one set of Repositories

If you’re really using the different DataSourcees in a multi-tenant kind of way (essentially assigning a request to a DataSource and sticking with it for the entire request) you should have a look at AbstractRoutingDataSource. It essentially provides a way to keep a Map of DataSourcees as well as a callback method to return a … Read more

org.hibernate.loader.MultipleBagFetchException: cannot simultaneously fetch multiple bags

Hibernate doesn’t allow fetching more than one bag because that would generate a Cartesian product. Now, you will find lots of answers, blog posts, videos, or other resources telling you to use a Set instead of a List for your collections. That’s terrible advice! Using Sets instead of Lists will make the MultipleBagFetchException go away, … Read more

JPA Select latest instance for each item

In SQL the solution is very simple – join the table with a subquery, which gives you the most recent meeting for each attendee: select * from Meeting ALL join ( select max(meetingDate) as newest, attendee from Meeting group by attendee ) LATEST on ALL.meetingDate = LATEST.newest AND ALL.attendee = LATEST.attendee This works, and works … Read more