hibernate,jpa,foreign-keys,entity,composite-primary-key , JPA, Hibernate can I do composite primary key which one element is foreign kay @OneToMany?

JPA, Hibernate can I do composite primary key which one element is foreign kay @OneToMany?


Tag: hibernate,jpa,foreign-keys,entity,composite-primary-key

I would like to have in my entity composite primary key consisting of 2 columns (attributes), and have one of them to be foreign key simultaneously.

I write something like this, but don't know whether it works cause foreign key is marked as generated value in IntelliJ data source

@Table(name = "service_point")
public class ServicePoint {

    private Long providerId;
    private Integer servicePointNumber;

    private Provider provider;

    @Basic(optional = false)
    @Column(name = "provider_id", nullable = false, insertable = false,
            updatable = false, columnDefinition = "BIGINT UNSIGNED")
    public Long getProviderId() {
        return providerId;

    public void setProviderId(Long providerId) {
        this.providerId = providerId;

    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "service_point_no", nullable = false, columnDefinition = "BIGINT UNSIGNED")
    public Integer getServicePointNumber() {
        return servicePointNumber;

    public void setServicePointNumber(Integer servicePointNumber) {
        this.servicePointNumber = servicePointNumber;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "provider_id")
    public Provider getProvider() {
        return provider;

    public void setProvider(Provider provider) {
        this.provider = provider;


I have tested Brian Vosburgh and it works:



ServicePoint servicePoint = new ServicePoint(provider, 1);



ServicePoint servicePoint2 = em.find(ServicePoint.class,
        new ServicePointId(provider.getUserId(), servicePoint.getServicePointNumber()));

assertTrue("Service point provider id and Provider provider id should be the same.",
        servicePoint2.getProvider().getUserId() == provider.getUserId());
assertNotNull("Service point number can not be null", servicePoint2.getServicePointNumber());
assertEquals(servicePoint2.getProvider(), provider);


UPDATE 2 - new problem in next relationship composite PK (3 columns) and 2 of them are composite FK I have been trying to resemble the below solution and couldn't get through how to write ServicePointPhotoId @IdClass

extentions of previous example


Get rid of the providerId field and its corresponding getter and setter. Add an @Id annotation to getProvider(). Define the IdClass like this:

public class ServicePointId {
    private Long provider;
    private Integer servicePointNumber;
    public Integer getProvider() {
        return provider;
    public void setProvider(Integer provider) {
        this.provider = provider;
    public Integer getServicePointNumber() {
        return servicePointNumber;
    public void setServicePointNumber(Integer servicePointNumber) {
        this.servicePointNumber = servicePointNumber;

Note that the property name in the IdClass matches the property name in the Entity (i.e. provider), but the properties' types are different. In the IdClass the property type must match the type of the Id property of Provider.

This is discussed in the JPA 2.1 spec, section 2.4.1.

Suggestion for UPDATE 2:

public class ServicePointPhotoId {
    public ServicePointId servicePoint;
    public Long photoId;

public class ServicePointPhoto {
        @JoinColumn(name="provider_id", referencedColumnName="provider_id"),
        @JoinColumn(name="service_point_no", referencedColumnName="service_point_no")
    private ServicePoint servicePoint;

    private Long photoId;

Note the attribute name must match (i.e. servicePoint); but the IdClass attribute's type must match the referenced Entity's IdClass (i.e. ServicePointId).

I have used field annotations, but you can convert those to property annotations.

Again: the JPA 2.1 spec has an example of just this sort of relationship in section


JPA NamedNativeQuery syntax error with Hibernate, PostgreSQL 9

I am having a rather odd problem. I have native query which runs perfectly when executed on sql server: SELECT date_time, GREATEST(sum(count_up - count_down) OVER (PARTITION BY date_trunc('day', result.date_time) ORDER BY date_time),0) AS cum_amt FROM peoplecounting.result order BY date_time; However, using this query as native query in JPA results in...

Spring Data JPA user posts

I have user login and profile view, I would like the users to have posts. Can someone guide me in the right direction? I have a user entity: @Entity @Table(name = "usr", indexes = { @Index(columnList = "email", unique = true) }) // using usr because in may conflict with...

HQL order by expression

I have two persistent classes, Comment and Vote. A Comment can be associated with many Votes and there is a @OneToMany - @ManyToOne relationship between them that's working correctly. What I'm trying to do is to sort the comments by most upvotes. A Vote is an upvote if Vote.up column...

Sqlite JPA Primary Key error

Hello i have a Problem with Sqlite and JPA. I have the following table in Sqlite: Section: secID INTEGER Primary Key secname TEXT If I use Primary Key in Sqlite this Value will automatically updated when i insert a value like INSERT INTO Section(secname) VALUES("Default"); In my Java Classes i...

multiple update with jpa

I need to upgrade a field of several records in bd. How to do this with JPA?. I tried the following but not working: @Override public String estadoPedido(List<DetallePedido> lista) { int cod; String mensage = null; for (DetallePedido ped : lista) { cod = ped.getIdDetalle(); EntityManager em = emf.createEntityManager(); DetallePedido...

Bean Creation exception, Injection of autowired dependency failed

I'm using spring hibernate in my application. I used all the required jar files but still getting bean creation exception saying the following: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'voteController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.mindtree.service.VoteService com.mindtree.controller.VoteController.voteService; nested exception is...

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) doesn't work

I need to delete a list of employees ignoring any integrity constraints (i.e. successfully delete the entity that doesn't related to any others yet or skip the entity that related to others) using JPA 2.0 and EJB3.0 on glassfish3.0: I iterated on the list and call entity manager in a...

Unidirectional one-to-many mapping in Hibernate generates redundant updates

I have defined two classes, Parent and Child. The parent can have a list of children. @Entity public class Parent { @Id @GeneratedValue(...) @SequenceGenerator(...) private long id; @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL) @JoinColumn(name = "parent_id", referencedColumnName = "id", nullable = false) private List<Child> children; public Parent() { children =...

Transaction error in Spring

I have a project https://github.com/ivartanian/onlinecontrol in Spring MVC + JPA, initially worked with the Spring configuration through XML. Now I am trying to set up the project through JAVA Config (without XML). The project starts, but when I create a new user(entity User), an error transaction. But if I create...

Can't Override Equals method on Java when calling contains

I have the following funtion that checks if a List of codigos contains a single codigos object: if (!concorrente.getJcodigoses().contains(cod)) { return "redirect:" + referrer; } I read that i need to Override the equals method like so: @Override public boolean equals(Object object) { boolean isEqual= false; if (object != null...

How can implement long running process in spring hibernate?

as we know the struts interceptor execute and wait will take care of long running process by not getting the request to timeout and destroy it sends wait and at last the desired response i want to implement the same for long running process in spring and hibernate. Thanks....

What are Relational Objects?

I am referring to this http://www.tutorialspoint.com/jpa/jpa_architecture.htm for learning JPA ,Here a table is given In query row what is relational object they are referring to? Are they the objects of entity classes which I am making or something else....

Use alternative producers of EntityManager / EMF in integration tests

I looking for way how to use CDI and alternative producers in integration tests. When i speak about producers, i mean EMF producer. Reason for different EMF producer is that i want to use testing in-memory database (different persistence unit). Is there easy way how to start CDI for integrations...

unexpected token : ( subquery hql

Here's my HQL query FROM com.mysite.ActeurInterne act WHERE act.acteurId IN (SELECT DISTINCT COALESCE(acteurInterne.acteurInternePrincipalId, acteurInterne.acteurId) FROM (SELECT DISTINCT acteurInterne FROM com.mysite.ActeurInterne AS acteurInterne JOIN acteurInterne.roleSet.roles AS role WHERE acteurInterne.acteurId = acteurInterne.acteurId AND acteurInterne.nom LIKE :likenom AND (role.dateFermeture IS NULL OR role.dateFermeture >= TRUNC(SYSDATE)) AND (role.dateOuverture IS NULL OR role.dateOuverture <= TRUNC(SYSDATE))...

Input data-validation in a restful web service (to use null-object or not to)

Below is a web service which gives the latest version among all books with a given Id. //Resource controller @Path("latestVersionBook/{id}") @GET @Produces(MediaType.APPLICATION_JSON) public Response getLatestVersionBook(long id){ bookList=service.getLatestVersionBook(id) return Response.ok(bookList).build(); //backend Service Below is the service method that uses jpa to get the books public getLatestVersionBook(long id){ Query query = entityManager.createQuery("from...

Optimistic locking not throwing exception when manually setting version field

I have a Spring Boot 1.3.M1 web application using Spring Data JPA. For optimistic locking, I am doing the following: Annotate the version column in the entity: @Version private long version;. I confirmed, by looking at the database table, that this field is incrementing properly. When a user requests an...

Hibernate delete child when parent is getting updated in same transaction

I have defined two entities Customer and SalesOrder in my domain model with oneToMany relationship from customer to salesOrder. Below code deletes the sales order: SalesOrder salesOrder = salesOrderRepository.findByOrderNumber(orderNumber); if(null != salesOrder){ Customer customer = salesOrder.getCustomer(); customer.setCurrentCredit(customer.getCurrentCredit() - salesOrder.getTotalPrice()); Iterator<SalesOrder> iter = customer.getSalesOrders().iterator(); while(iter.hasNext()){ SalesOrder order = iter.next();...

Is it possible to have “connection preparation” with Spring / JPA persistency

I have a Spring CrudRepository that is just an interface, and I have a persistence context class where I have defined my data source: @Configuration @EnableTransactionManagement public class PersistenceContext { @Bean(name="dataSource", destroyMethod = "close") public DataSource dataSource() throws SQLException { return ... public interface DataRepository extends CrudRepository<Data, Long> { Data...

Can't obtain connection with the DB due to very long schema validation and connection reset afterwards

I have an app where I use Hibernate/Oracle 11g XE/Jboss6.2 and I am having trouble starting up the application on my homolog server at DigitalOcean (Jboss and Oracle xe installed locally). Running everything on my dev machine I have no problem at all and it starts in about 30s, but...

Updating Database Directly and Bypassing Hibernate - Does hibernate have a “Check and Clean All” feature?

People are executing update/insert/delete sql directly against the database, as opposed to using the APIs, thus bypassing Hibernate (don't ask, it just is). As such, the audit tables are not getting updated. Does hibernate contain some kind of "Check and Clean All" feature that will update the audit tables or...

could not resolve property: userId.username

I have following entity classes: @MappedSuperclass public class AbstractEntity implements Serializable, Comparable<AbstractEntity> { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "id") protected Integer id; @Override public int compareTo(AbstractEntity o) { return this.toString().compareTo(o.toString()); } public Integer getId() { return id; } public...

Hibernate criteria accepting %% value

I am using the below Hibernate code to filter workFlowName. crt.add(Restrictions.like("workFlowName", workFlow, MatchMode.ANYWHERE)); // crt is the criteria The problem is when I pass the value to workFlow from web (TextBox).it fetching the value correctly (I am passing sym in text box if fetch 10 records.if i pass the same...

OpenJPA OneToMany and composite key in parent and child table

I have tables with composited primary key. Server(key=ServerId) ServerId|Name 1 |server1 2 |server2 ParentObj(key=ServerId+Code) ServerId|Code |Title 1 |code1|value1 1 |code2|value2 2 |code1|Value2b ChildObj(key=ServerId+Code+Name) ServerId|Code |Name |Value 1 |code1|prop1|val1 1 |code1|prop2|val2 1 |code2|prop1|val1b 2 |code1|prop3|val3 This is Java beans I have. @Entity @Table(name="ParentObj") @Access(AccessType.FIELD) @IdClass(value=ParentObj.PK.class) @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER) @XmlRootElement public class ParentObj {...

Hibernate : Stale state exception

I am working on a Spring-MVC application in which I am trying to delete an object from the database. Some days back, this error all of a sudden started, and now I am unable to delete. I checked on net, but I cannot find what am I doing wrong and...

JPA annotation for MS SQL Server 2008 R2 IDENTITY column

I want to know proper JPA annotation setup to handle MS Server 2008 R2 IDENTITY column. MS Server 2008 R2 (RTM) doesn't support SEQUENCE, but the IDENTITY gives auto increment when I tested by raw sql. However, by JPA I can't make it work by any strategy (IDENTITY, AUTO, TABLE)...

How to call MySQL view in Struts2 or Hibernate

I have a view in MySQL database CREATE VIEW CustInfo AS SELECT a.custName, a.custMobile, b.profession, b.companyName, b.annualIncome FROM customer a INNER JOIN cust_proffessional_info b ON a.cust_id=b.cust_id Is there any way that i can call this view using Struts2 or in Hibernate. I have tried to search it but could not...

Spring Boot - How to set the default schema for PostgreSQL?

What I am currently doing in my application.properties file is: spring.datasource.url=jdbc:postgresql://localhost:5432/myDB?currentSchema=mySchema Isn't there another property for this? Since it looks hacky and according to a post (still finding the link sorry, will update later), it is only applicable to PostgreSQL 9.4....

Spring Boot extending CrudRepository

I'm using Hibernate in a Spring Boot app. I'm making a new CrudRepository for all my Model objects, to do basic CRUD tasks. They look like this: @Repository public interface FoobarCrudRepo extends CrudRepository<Foobar, Long> { } But then I always need to do some additional things, like custom search queries...

Making an efficient query with 7 joins, JPA or SQL? What type of collection?

folks! Had to performance tune an expensive JPA query with 7 joins, taking 42 seconds to complete locally and ~3 minutes in the remote server (AWS). SELECT res FROM Resultado res JOIN res.panoramica pan JOIN pan.gondolaId gon JOIN gon.visitaId vis JOIN vis.estabelecimentoId estab JOIN estab.cliente cli JOIN res.configuracaoAnalise ca JOIN...

Blocking Updating or Inserting an Entity when using Cascade in Hibernate

I have an entity , EntHesaplasma , this entity has a relationship with EntCariHareketler entity. I have a foreign key in the EntHesaplasma entity for EntCariHareketler. I want to set a relationship between them , but I dont want to update,insert or remove operations on EntCariHareketler entity. Only I want...

performance of executing openjpa query

I have a rest web app with cxf 3.0.1 framework and openjpa 2.3.0. The web.xml: <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name>Mobile app rest services</display-name> <context-param> <param-name>contextConfigLocation</param-name> <param-value>WEB-INF/cxf-servlet.xml</param-value>...

All I want is to access a H2 mem database in Websphere V8 using JPA 2.0

I've been struggling with this for days now and I searched dozens of articles in StackOverflow and other dev sites. I used the Deployment Manager interface to configure a Websphere Application Server with a H2 JDBC provider and a Data Source for my application using a tutorial I've found...

Hibernate Primary Key annotation returns null value

i am following http://viralpatel.net/blogs/hibernate-one-to-one-mapping-tutorial-using-annotation/ for learning primary key annotation. I have two classes @Id @Column @GeneratedValue(strategy=GenerationType.AUTO) private int id; private String firstName; private String lastName; private String email; private String password; private String profession; @OneToOne(mappedBy="user" , cascade=CascadeType.ALL) private Profile profile; and my profile class @Id @Column @GeneratedValue(strategy = GenerationType.AUTO) private...

How to know an object has changed compared to database

I need to know if some fields of a model object has been changed before save because I need to compare the new values with the old ones. I can't touch the model classes are they are generated. My problem is that whenever I change an object in a controller...

JPA and Apache Aries: persistence unit unresolved dependency

I'm trying to configure a datasource for mysql and a corresp. persistence bundle on top of Apache Aries. This is the datasource's blueprint file <bean id="mysqlDataSource" class="com.mysql.jdbc.jdbc2.optional.MysqlDataSource"> <property name="url" value="jdbc:mysql://matteos-mbp:3306/" /> <property name="user" value="root" /> <property name="password" value="root" /> <property name="databaseName" value="testDBBlueprint" /> <property name="createDatabaseIfNotExist" value="true" /> </bean> <bean...

what is gradle missing to map hibernate?

I have unittest to my java project. My code uses hibernate. When i run the test using junit - everything passes. When I run the test using gradle - I get a mapping error: Caused by: org.hibernate.MappingException: Unknown entity: linqmap.users.interfaces.model.UserRecord and the class: @Entity @Table(name = "users") public class UserRecord...

Spring-MVC, Hibernate : Creating DTO objects from Domain objects

I am working on a Spring-MVC application in which I am trying to search for List of GroupNotes in database. The mapping in my project is GroupCanvas has one-to-many mapping with GroupSection and GroupSection has one-to-many mapping with GroupNotes. Because of these mappings, I was getting LazyInitializationException. As suggested on...

Checking for multiple child constraint violations in Hibernate/JPA

TL;DR: Is it possible to perform nested transactions in Hibernate that use SavePoints to rollback to specific states? So I am attempting to persist a parent entity with a OneToMany mapping to child entities. This is working fine. During this persistence, I would like to catch and log ALL constraint...

How to delete multiple rows in Hibernate

I tried to delete multiple rows from database using Hibernate. Its successfully done. When I refresh the .jsp page, the deleted items will shown again. Here's my code: public int deleteUserById(String id[]) { SessionFactory sf = HibernateUtil.getSessionFactory(); int flag = 0; User user; try { for (int i = 0;...

@Resource datasource breaking DB connection

I recently wrote a class, in my web application, for parsing a huge XML file and feed a db table with its content. My application is running on Wildfly9, and uses JPA with Hibernate provider to handle a MySQL DB. The AS configuration is pretty standard, I just added my...

Java JPA EM.createNativeQuery(sql, someClass).getResultList()

How do I return a list of foobar as below? @MappedSuperclass public abstract class foobar{} @Entity @Table(name="foobar") public class foo extends foobar{} @Entity @Table(name="foobar") public class bar extends foobar{} List<foobar> results = em.createNativeQuery("SELECT * FROM foobar").getResultList(); Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to foobar....

very high float value changing to infinity while retrieving from database

I have an entry in my database select item_numeric_value from Item_Allowed_Values where id=761 datatype of item_numeric_value is float in my db. the result I get is 1.11111111111111E+49. when I retrieve this value in java in a string , I get infinity. is there anything I am missing or doing wrong ?...