FAQ Database Discussion Community


Java SingleTable inheritance in db structure using JPA/Hibernate

java,hibernate,jpa,single-table-inheritance
I have models/Entities as follow: @Entity @DiscriminatorColumn(name="type") @Inheritance(strategy=InheritanceType.SINGLE_TABLE) public class Insurance extends Generic<Insurance> { @OneToOne public myInsurance.models.liability.hivAndVHProtection.Hiv_Answer hivAndVHProtectionAnswer; } @MappedSuperclass @Inheritance(strategy=InheritanceType.TABLE_PER_CLASS) public class Answer extends Generic<Answer> {} @Entity @Inheritance(strategy=InheritanceType.SINGLE_TABLE) @DiscriminatorValue("A") public class Hiv_Answer extends...

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

java,jpa,jdbc,websphere,persistence.xml
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 8.0.0.3 with a H2 JDBC provider and a Data Source for my application using a tutorial I've found...

JPA AccessType.Property failing to retrieve value from nested classes

java,jpa,persistence
I'm attempting to parse JSON into an @Entity in order to persist the data in a table. I confirmed the parsing works but I have run into an issue when attempting to persist the data. In order to retrieve the needed value in the nested classes (two deep) I am...

org.hibernate.ejb.event.EJB3MergeEventListener missing after upgrading from Hibernate 3 to 4.3.9

java,hibernate,jpa,ejb
I am trying to upgrade from Hibernate 3.6.10 to 4.3.9 (and JPA 2.0 to 2.1). Some code in my application uses the org.hibernate.ejb.event.EJB3MergeEventListener class, which used to be in the hibernate-entitymanager jar, but is missing from the 4.3.9 version. From what I can tell, it was removed as of 4.3,...

DTOs and entities which implements the same interface

java,android,spring,hibernate,jpa
I have the next maven projects: project-model : I have JPA entities project-rest : Spring data, spring rest based on spring boot project-client : Jersey clients to consume the rest services project-web : Only jsf web application project-desktop : Java Fx desktop application project-android : Mobile application which consumes my...

very high float value changing to infinity while retrieving from database

java,mysql,sql-server,hibernate,jpa
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 ?...

JPQL In clause error - Statement too complex

jpa,derby,jpql
Following is the code which is blowing up if the list which is being passed in to "IN" clause has several values. In my case the count is 1400 values. Also the customer table has several thousands (arround 100,000) of records in it. The query is executing against DERBY database....

Spring JPA - default value for enum field in enum

java,spring,hibernate,jpa,enums
We have an entity with an enum field - emailCommunicationStatus, and we want to set a default value for it using JPA annotations - 'UNKNOWN'. However, when we save the entity to the DB, the value of this field is null and not . For the boolean field - isLocked...

Spring-boot+JPA EntityManager inject fails

spring,java-ee,jpa,spring-boot,cdi
In my J2EE application I try to use spring-boot and JPA technologies with injection of EntityManager into DAO layer. However, I have some problems... My repository for user CRUD: @Repository public class UserRepositoryImpl implements UserRepository { @PersistenceContext(unitName = "data") private EntityManager entityManager; // and crud methods } My spring-boot application...

JPA persit creates new existing entity in many to one relation

java,hibernate,jpa,insert
I'm new in JPA and I have de following Entities in my project : Animal entity : package com.shop.model; import java.io.Serializable; import javax.persistence.*; @Entity @NamedQueries({ @NamedQuery(name="Animal.findAll", query="SELECT a FROM Animal a"), @NamedQuery(name="Animal.findAllByTypeId", query="SELECT a FROM Animal a WHERE a.type.id = :id"), }) public class Animal implements Serializable { private static...

Checking for multiple child constraint violations in Hibernate/JPA

spring,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...

Transaction error in Spring

java,spring,jpa
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...

javax.persistence.Persistence.getPersistenceUtil()Ljavax/persistence/PersistenceUtil

java,spring,hibernate,maven,jpa
In a Spring-MVC application I try to use the validators. I put the annotation @NotEmpty and @Email on one of my entity and when I try to validate it I get this error: java.lang.NoSuchMethodError: javax.persistence.Persistence.getPersistenceUtil()Ljavax/persistence/PersistenceUtil; at org.hibernate.validator.engine.resolver.JPATraversableResolver.isReachable(JPATraversableResolver.java:33) at org.hibernate.validator.engine.resolver.DefaultTraversableResolver.isReachable(DefaultTraversableResolver.java:112) at...

OpenJPA OneToMany and composite key in parent and child table

java,jpa,jpa-2.0,openjpa
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 {...

JPA ERROR: relation does not exist

java,postgresql,jpa,runtime-error,eclipselink
I can't figure out what I'm doing wrong. I'm learning JPA mapping to a relational DB, by following some tutorials on the web, but can't find one that is straightforward. When I run my project, it gives me an error. I guess it's upon persisting em.persist();. If I comment that...

Querying a nullable @OneToOne relationship with JPA

java,sql,hibernate,jpa,jpql
I have Entity1 and Entity2. They have a OneToOne nullable relationship. @Entity class Entity1 { @Id @Column(name = "id") private Long id; @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "entity2") @JoinColumn(nullable = true) private Entity2 entity2; ... } How can I query all Entity1 objects that has a null...

multiple update with jpa

java,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...

How to create forms for multiple database tables?

java,spring,jpa,spring-data-jpa
I have an application that processes text files. Depending on the file generator, it searches for some defined texts. Then it executes different actions on the found texts. These actions are stored in a database and correspond to the following entities: @Entity @Table(name = "file_generator") public class FileGenerator { @Id...

Hibernate/JPA: Check generated sql before updating DB Schema (like .NET EF migrations)

java,hibernate,jpa
So i am trying to learn Hibernate/JPA and i was wondering if there is something similar to .NET's Entity Framework migrations that i can use. I like Code First (Class -> Schema) approach, but the auto generated sql queries may do strange (and dangerous) things to a database. I want...

jsf - foreign key in datatable

jpa,datatable
I'm showing a list of Orders in a datatable , and one of its columns must show the customer_id of that order: customer_id is a fk in ManyToOne relationship. Customer entity @Entity public class Customer { ///other columns @OneToMany(mappedBy = "cliente", fetch=FetchType.EAGER) private List<Order> orders; Order entity @Entity @Table(name =...

Bidirectional relationships in JPA

hibernate,jpa,eclipselink,jpa-2.1,bidirectional-relation
I am missing something very fundamental. Given below two entities Department (inverse side) and Employee (owning side) forming a one-to-many relationship from Department to Employee. Department.java @Entity @Table(catalog = "testdb", schema = "", uniqueConstraints = { @UniqueConstraint(columnNames = {"department_id"})}) public class Department implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional...

Spring 4 + JPA (Hibernate 4) + JTA transaction manager doesn't flush automatically

java,spring,hibernate,jpa,transactions
I am migrating an application from Spring 3.0.5 + JPA 2.0 to Spring 4 + JPA (Hibernate 4) I have followed the migration guide : https://github.com/spring-projects/spring-framework/wiki/Migrating-from-earlier-versions-of-the-spring-framework. The application is using a JTA transaction manager : a Jencks / GeronimoPlatformTransactionManager (because of transactions distributed on datasources and ESB). The Spring /...

@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) doesn't work

java,jpa,glassfish,ejb-3.0
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

java,hibernate,jpa
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 =...

JSF Controller, Service and DAO

jsf,java-ee,jpa,ejb,dao
I'm trying to get used to how JSF works with regards to accessing data (coming from a spring background) I'm creating a simple example that maintains a list of users, I have something like <h:dataTable value="#{userListController.userList}" var="u"> <h:column>#{u.userId}</h:column> <h:column>#{u.userName}</h:column> </h:dataTable> Then the "controller" has something like @Named(value = "userListController") @SessionScoped...

Hibernate's ManyToMany simple use

java,spring,hibernate,jpa,many-to-many
I've two entities : CollabEntity and TechnoEntity. A collab can uses several technos. A techno can be used by several collabs. I would like to know all technos used by a specific collab. My DB looks like : CREATE TABLE collabs( co_id INT PRIMARY KEY NOT NULL AUTO_INCREMENT, co_firstname VARCHAR(25)...

Concurrency of JPA when same DB used by other applications

java,spring,jpa,concurrency
I am developing a Spring MVC JPA web application. When this application is deployed in live the same DB that my application interacts with will be used by other 2 Dotnet and VB applications at the same time. I am managing the concurrency of my JPA app through version column....

distinct & trim in JPA with hibernate 3.2.6

oracle,hibernate,jpa
Is there a way to do select distinct trim(addressInfo.city) in JPA ? I got this error (without the trim it works fine) Caused By: java.sql.SQLSyntaxErrorException: ORA-01791: not a SELECTed expression at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:445) at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:396) at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:879) at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:450) at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:192) Truncated. see log file for...

Do I need to annotate JPA actions with @Transactional in Play Framework-1.x to prevent the connection leak?

jpa,transactions,playframework-1.x,transactionmanager
As described here (relevant parts), https://www.playframework.com/documentation/1.3.x/jpa Play will automatically start the Hibernate entity manager when it finds one or more classes annotated with the @javax.persistence.Entity annotation... When the JPA entity manager is started you can get it from the application code, using the JPA helper... Play will automatically manage transactions...

Hibernate: embedded id field naming issue

java,hibernate,jpa
I have an entity CashFlow which has a field category of entity class CashFlowCategory. The latter has a composite key consisting of fields name and username. In database these fields are called NAME and USERNAME. The app was working fine with EclipseLink but when I tried to switch to Hibernate...

Efficient way to get last record from the database

mysql,database,jpa,query-optimization
I have a database with following table structure : id | entry | log_type | user_id | created_on | ------------------------------------------------| 1 |a | error | 1 | 1433752884000| 2 |b | warn | 2 | 1433752884001| 3 |c | error | 2 | 1433752884002| 4 |d | warn | 4...

JCR vs JPA for a DMS: performance, benefits, drawbacks

java,jpa,jcr,jackrabbit,dms
After doing some research about JCR or RDBMS, and reading other posts, I am still uncertain whether to use JCR over JPA for a document management system, which has to deal with different document types, very large files and a lot of concurrent access from many users. My main reason...

unexpected token: part near line 1, column 155 [SELECT NEW

java,jpa,jpql
I am getting an error and I can only assume there is something wrong with my query. I am trying to initialize a class with the "new" key word in JPQL like so: @Query("SELECT NEW com.htd.domain.ShopOrder(po.id, po.po_number, " + "po.due_date, po_part.id, po_part.part_quantity, " + "part.id, part.part_number, part.part_description " + "part.plasma_hrs_per_part,...

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

java,spring,jpa,spring-data
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...

javax.validation.ConstraintViolationException: Bean Validation constraint(s) violated while executing Automatic Bean Validation on event:'prePersist'

hibernate,jpa,eclipselink,bean-validation,jsr303
Given two entities Department and Employee forming a unidirectional one-to-many relationship from Department to Employee based on respective tables in the database in question as follows. public class Department implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "department_id", nullable = false) private Long departmentId; @Size(max =...

Maven “clean install site” fails for JPA Metamodel generated classes

java,hibernate,maven,jpa
I am working on a JPA/Hibernate application which generates the JPA Metamodels using maven-processor-plugin <plugin> <groupId>org.bsc.maven</groupId> <artifactId>maven-processor-plugin</artifactId> <version>2.2.4</version> <executions> <execution> <id>process</id> <goals> <goal>process</goal> </goals> <phase>generate-sources</phase> </execution> </executions> <dependencies> <dependency>...

JPA truncates nanoseconds when using date criteria & SQL datetime2

java,sql-server,hibernate,jpa,datetime2
I'm trying to create a where clause involving a SQL Server datetime2 field (accurate to 100 nanoseconds); using JPA & Hibernate. My code looks something like this: CriteriaBuilder cb = em.getCriteriaBuilder(); List<Predicate> predicates = new ArrayList<>(); CriteriaQuery(X) q = cb.createQuery(X.class); Root<X> root = q.from(X.class); java.sql.Timestamp mySqlTimeStamp = Timestamp.valueOf("2015-06-04 11:31:53.2119339"); predicates.add(cb.greaterThan(root.get("DateModified"),...

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

java,mysql,jpa,join
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...

Retrieve the id of an Entity object as soon as the entity was instantiated?

jsf,jpa
Is there a way in JPA to retrieve the id of an Entity object as soon as the entity was instantiated? e.g Person person = new Person(); Currently i am using in my entity class the following strategy: @GeneratedValue(strategy = GenerationType.IDENTITY) If not is there a "Dummy Id" strategy for...

Is possible do not fetch eager relation in JPA?

hibernate,jpa
I have relation annotated as following: @OneToMany( fetch = FetchType.EAGER ) Is possible to do not fetch this relation without changing default fetch type to lazy? I ask obout it because I improve existing application and I don't want to change existing entities and their annotations. In my case I...

Why JPA entities are treated like this outside a session?

jpa,entity
Hy, I am having a "Solve failed to lazily initialize a collection of role.... exception" in jpa. I understand that outside a session, when you want to retrieve a lazy collection if there is not session bound you will get this error, fine. But what I dont understand is if...

Adding a newly persisted entity to a list of entities held by the inverse side of a relationship so as to maintaining a bidirectional relationship

java,hibernate,jpa,hibernate-mapping,bidirectional-relation
Given two entities Department and Employee forming a one-to-many relationship from Department to Employee. Since the relationship is quite intuitive, I am leaving out the entity classes. The following segment of code, simply persists an entity Employee. public void insert() { Employee employee = new Employee(); employee.setEmployeeName("k"); Department department =...

Hibernate's bidirectional OneToOne relationship not working within the same class

java,hibernate,jpa,hibernate-mapping
I'm trying to create "a chain of commands" using One to One hibernate relationship withing the same class: @Entity public class Command { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", unique = true) private Long id; @ElementCollection @LazyCollection(LazyCollectionOption.FALSE) private List<String> commandWithArguments = new ArrayList<String>(); private ExecutionStatus status = ExecutionStatus.NOT_EXECUTED; @OneToOne(mappedBy...

Hibernate constraint fails on cascade save

java,spring,hibernate,jpa
I have problem with cascade save of related entities. My UserEntity is related "one to many" with RegistrationTokenEntity. When I try to save this entities cascaded I get exception. Here is code: UserEntity: @Entity @Table(name = "user", schema = "", catalog = "myDatabase") public class UserEntity { private int userId;...

Optimistic locking not throwing exception when manually setting version field

hibernate,jpa,spring-data-jpa
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...

JPA annotation for MS SQL Server 2008 R2 IDENTITY column

hibernate,sql-server-2008,jpa,spring-data-jpa
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)...

Hibernate Query cache invalidation

java,hibernate,jpa,caching,concurrency
I am using Hibernate(with JPA) in an application that has a high write-read ratio. For caching I have enabled query-cache and hibernate second level cache(ehcache). The problem I am facing is due to automatic query cache invalidation when an update is done. Is there any way to configure query cache...

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

java,jpa
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....

JPA NamedNativeQuery syntax error with Hibernate, PostgreSQL 9

java,hibernate,postgresql,jpa
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...

When NOT to use EntityManager.flush()?

java,jpa,eclipselink,entitymanager,flush
For synchronization and to retrieve the DB-generated ID's I feel coerced to call EntityManager.flush() at several places. Performance implications aside, are there reasons not to call flush()? In other words, is there any observable difference for the caller of my (DAO, ...) method if it does/doesn't flush()? My scenario is...

Cache inconsistency - Entity not always persisted in cached Collection

java,hibernate,jpa,caching,ehcache
I'm having an issue where a Validation instance is added to a Collection on a Step instance. Declaration is as follows: Step class: @Entity @Table @Cacheable @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) public class Step extends AbstractEntity implements ValidatableStep { @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true) @JoinColumn(name = "step_id", nullable...

HIbernate: Found two representations of the same collection

java,hibernate,jpa
Working with Hibernate-EntityManager 4.3.5 I'm getting the HibernateException: Found two representations of the same collection. The scenario is that I have 2 entities A and B; both with relationship to a third entity C. A also have a relationship with B. Let's try to make it clear: A -> OneToOne...

Caused by: java.sql.SQLSyntaxErrorException: [SQL0205] Column MITMAS_MMCONO not in table OOLINE in schema

spring,hibernate,jpa,left-join,spring-data
I have 3 entity classes Ooline: @Entity @IdClass(OolineId.class) @NamedQuery(name="Ooline.findAll", query="SELECT o FROM Ooline o") public class Ooline implements Serializable { private static final long serialVersionUID = 1L; @ManyToOne(fetch = FetchType.LAZY) @JoinColumns({ @JoinColumn(name="mitmas_mmcono" , referencedColumnName="mmcono"), @JoinColumn(name="mitmas_mmitno" , referencedColumnName="mmitno") }) private Mitmas mitmas ; @ManyToOne(fetch = FetchType.LAZY) @JoinColumns({ @JoinColumn(name="mitfac_m9cono",...

Spring Data JPA user posts

java,spring,jpa,data
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...

Including all @OneToMany Entities in Restful-WebService response?

java,web-services,rest,jpa,bidirectional-relation
First Post here,so please excuse any noobish approaches to best get your attention / help me you find an answer. :) Without going into too much detail of my actual Program: I have a User who can register many Devices which can be associated to many Remotes which can have...

jpa map owned by the “one” side

java,jpa,bidirectional-relation
I have a tree like data structure with some sort of composite pattern. With an abstract class Element, there is a CompositeElement and a SingleElement. It looks like this: @Entity @DiscriminatorValue("Composite") public class CompositeElement extends Element { @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER) @JoinTable(name="Sub_Elements") @MapKeyColumn(name="xxx") protected Map<Integer, Element> subs; ... } Until now, the...

How to create nested selects with sql?

java,sql,jpa
I want to select all entities that are tied by a custom hierarchy: @Entity class Employee { @Id private long id; @ManyToOne private Company company; } @Entity class Company { @Id private long id; @ManyToOne private LeisureGroup leisureGroup; } @Entity class LeisureGroup { @Id private long id; } //select all...

Getting java.lang.NoSuchFieldError: ERRORS_IGNORED for hibernate-ogm with mongodb

mongodb,hibernate,jpa,hibernate-ogm
I am trying to use hibernate-ogm with mongodb and getting no such fieds error persistence.xml <persistence-unit name="mongodb-test" transaction-type="JTA"> <provider>org.hibernate.ogm.jpa.HibernateOgmPersistence</provider> <properties> <property name="hibernate.ogm.datastore.provider" value="mongodb"></property> <property name="hibernate.ogm.datastore.host" value="192.168.0.237"></property> <property name="hibernate.ogm.datastore.create_database"...

JPA add child record - have 3 copyes of it in parent

java,jpa
I have News entity and comment entity. I want to create news with 0 comments and then add some comments to this news. In DB I have table NEWS for news info and news_id column in COMMENTS table. News.java: @Entity @Table(name = "NEWS") public class News implements Serializable{ /** *...

How to store an entity together with its relations?

java,spring,jpa,spring-data-jpa
Imagine the following entities: @Entity public class Car { @Id @GeneratedValue private long id; private String manufacturer; private String model; @OneToMany(mappedBy = "car") private Set<Tire> tires = new HashSet<>(); // Getters & setters } @Entity public class Tire { @Id @GeneratedValue private long id; @ManyToOne @JoinColumn(name = "car_id") private Car...

Blocking Updating or Inserting an Entity when using Cascade in Hibernate

java,hibernate,jpa,orm,hibernate-mapping
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...

Hibernate with Sql Server fail for nvarchar field with “No Dialect mapping…”

java,sql-server,hibernate,jpa
I'm using Hibernate's JPA-Implementation to access our SQL Server 2012 database. When trying to select a nvarchar field in a native query, I get an exception "No Dialect mapping for JDBC type: -9". It looks much like No Dialect mapping for JDBC type: -9 with Hibernate 4 and MS SQL...

What are Relational Objects?

database,jpa,persistence
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....

JPA PersistenceException: Class name could not be resolved

java,google-app-engine,jpa,gae-datastore
I'm trying to create a method to get a project by the project name from GAE, but I'm getting the following error. javax.persistence.PersistenceException: Class name TestProject could not be resolved I get this error in the following piece of code on the line where the ifstatement starts public Project getProjectByProjectName(String...

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

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 @Entity...

JPA. JOIN nested SELECT “unexpected token (” [duplicate]

java,jpa,jpql
This question already has an answer here: HQL: Is it possible to perform an INNER JOIN on a subquery? 1 answer I have News entity and want to get list of news ordered by number of comments. I try to do it like this: Query query = manager.createQuery("SELECT n...

Segregating the read-only and read-write in Spring/J2EE Apps

mysql,jpa,design-patterns,architecture,spring-data
We using Spring, Spring-Data and JPA in our project. For production servers, we would like to setup database cluster such that all read queries are directed to one server and all write queries are directed to another server. This obviously will require some changes in the way the DAOs are...

use like for integer value in namedquery Eclipselink

java,jpa,eclipselink
when use namedQuery in entity class get error @NamedQuery(name = "Classification.search", query = "SELECT c FROM Classification c WHERE c.id LIKE :value") Method for call namedQuery public List<Classification> search(String value) { Query query = getEntityManager().createNamedQuery("Classification.search", Classification.getClass()).setParameter("value", "%"+value+"%"); query.setMaxResults(10); return query.getResultList(); } java.lang.IllegalArgumentException: You have attempted to set a value of...

Hibernate Search Faceting not working

java,hibernate,jpa,hibernate-search
I´m programming a web application with Java EE, Hibernate Search, JPA and JSF. I have been reading the hibernate Search documantation over and over again, but I just can´t get faceting to work properly. I have a database which includes several categorys. I made an example with football clubs. I...

JPA try to delete if fails set inactive

java,hibernate,jpa
i have the following entity A (imagine B as just a simple enitity with an active/inactive-flag which can be referenced by other entities) @Entity public class A { @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true) private B b; } i need to try to remove b, but if it is referenced...

org.hibernate.exception.SQLGrammarException: could not prepare statement; nested exception is javax.persistence.PersistenceException

java,spring,hibernate,jpa,spring-data
I have 3 entity classes Ooline: @Entity @IdClass(OolineId.class) @NamedQuery(name="Ooline.findAll", query="SELECT o FROM Ooline o") public class Ooline implements Serializable { private static final long serialVersionUID = 1L; @ManyToOne(fetch = FetchType.LAZY) @JoinColumns({ @JoinColumn(name="mitmas_mmcono" , referencedColumnName="mmcono"), @JoinColumn(name="mitmas_mmitno" , referencedColumnName="mmitno") }) private Mitmas mitmas ; @ManyToOne(fetch = FetchType.LAZY) @JoinColumns({ @JoinColumn(name="mitfac_m9cono",...

Can I make this request more efficient using index?

java,mysql,sql,jpa
I have this bean/table "Userinfo" with columns id, username, and twitchChannel. For most userinfo the twitchChannel column will be null. I'm going through every userinfo entity in the table and search the column twitchChannel, if the column is not null I put the twitchChannel in an array. this is what...

@Resource datasource breaking DB connection

java,jpa,jdbc,jboss,wildfly
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...

Not persisted entity with Hibernate

java,spring,hibernate,jpa
I have created this code: Sale sale = new Sale(); saleService.create(sale); Vendor vendor = new Vendor("name"); Sale updatedSale = saleService.findById(sale.getId()); updatedSale.setVendor(vendor); try { saleService.update(updatedSale); } catch (EntityNotFoundException ex) { System.err.println(""); } Also, sale is in cascade with vendor: @ManyToOne(cascade={CascadeType.PERSIST,CascadeType.REFRESH}, targetEntity = Vendor.class) @Cascade({ org.hibernate.annotations.CascadeType.SAVE_UPDATE, org.hibernate.annotations.CascadeType.PERSIST })...

Try to save new Entitiy in Database but generated ID is null

java,spring,hibernate,jpa,h2
I have an object "Event" and an object eventDetails. Both are jpa Entities. The Event object contains the eventDetails by a @OneToOne annotation. My Database has lots of events. But the eventdetails of every event are null. In my RestController I try to fill the eventdetails like this: @RequestMapping(value =...

JPA - how to prevent an unnecessary join while querying many to many relationships

java,hibernate,jpa,pagination,spring-data
I have entities Product and Category that are joined with a simple many to many relationship. I want to get a paginated list of products filtered by a single category. I'm trying to write a Spring Data JPA automatic method or a JPQL query method that would produce the SQL...

Loading Image into byte array in entity bean

spring,hibernate,jpa
I am using spring data jpa and hibernate to retrieve entities from a DB table. One of the entity fields is the path to an image which is located on the filesystem. is it possible to load the image as a byte array into an entity? e.g @Entity @Table(name="Users") public...

Using the new operator in JPQL to initialize a constructor

hibernate,jpa,jpql
I am trying to initialize a class called ShopOrder which looks like: public ShopOrder(int po_id, long po_number, Date po_due_date, long po_part_id, int part_quantity, int part_id, int part_number, String part_decription, long plasma_hrs, long gring_hours, long mill_hrs, long breakpress_hrs) { By doing the following: @Query("SELECT new ShopOrder(po.id, po.po_number, " + "po.due_date, po_part.id,...

Using tapestry-jpa just with tapestry-ioc in non-web project

jpa,tapestry
this is a very basic question, and I'm kind of sorry, but I don't seem to be able to get a simple Tapestry-IOC based application to work with the built-in Tapestry JPA module. The application is not necessarily meant as a web project so the dependencies are just tapestry-ioc and...

Drools Stateful Knowledge Session using persistence

java,jpa,jdbc,drools,jbpm
I am creating a Drools stateful session as described in the JBPM persistence documentation: http://docs.jboss.org/jbpm/v5.1/javadocs/org/drools/persistence/jpa/JPAKnowledgeService.html However, I came across the following exception javax.persistence.TransactionRequiredException: joinTransaction has been called on a resource-local EntityManager which is unable to register for a JTA transaction. My code is : EntityManagerFactory emf = Persistence.createEntityManagerFactory("metadata.model"); Environment env...

Hibernate @OneToOne child not persisting

java,spring,hibernate,jpa,spring-roo
I have a Stock entity which has 2 child entities, stock can only be vehicle or property, not both, stock is defined as follows: @RooJavaBean @RooToString @RooJpaActiveRecord public class Stock { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id") private Long id; @Version @Column(name = "version") private Integer version; ... @OneToOne(mappedBy...

JPA difference between transaction isolation and entity locking

java,database,jpa,concurrency,transactions
I have read about transaction isolation levels. It is used to prevent parallel transaction executions errors. Its quite obvious. There are also locking modes available for entities. I understand how they work. But I cant find the reason why I need locking? I have used transaction isolation levels already. Why...

Is it possible to connect a JPA implementation to a Neo4j specific version?

jpa,neo4j,datanucleus,kundera,hibernate-ogm
I have a Java project that use an embedded Neo4j database (NoSQL), version 2.0.0. I need to migrate this data for a traditional relational db (SQL). For this job, I thought that using an implementation of JPA could help. I found these three projects: Hibernate OGM DataNucleus Kundera But I...

Get id column name from POJO, using reflection

java,jpa,reflection,annotations
@Entity @Table(name="MY_TABLE") public class MyTable{ @Id @Column(name="MY_TABLE_ID") @GeneratedValue(strategy = GenerationType.AUTO ,generator="SQ_MY_TABLE") @SequenceGenerator(name="SQ_MY_TABLE", sequenceName="SQ_MY_TABLE") private Long myTableId; How can I, using reflection, get the primary key column name from my POJO, defined with the javax.persistence.Id annotation? I'd have to find the @Id and then get the name property of the @Column...

Why is my EntityManager not properly injected?

jpa,ejb,wildfly,entitymanager
I tried to build a project with manages Employees using JPA and Beans and JSF. I started trying to manipulated an existing user which I manually created in the database. (before I tried to read the data from the database, this worked well) I tried this in various ways, by...

JPA - How to query with a LIKE operator in combination with an AttributeConverter

java,jpa,criteria-api
For example Customer has a field of type PhoneNumber (value object). In the persistence.xml a PhoneNumberConverter is registered which implements javax.persistence.AttributeConverter. This converter converts a PhoneNumber to string and visa versa, so the JPA provider is able to store PhoneNumbers into the database. How to query a Customer with a...

JPA not receiving updated data

java,jpa,persistence
I use a managedBean that goes into the db and defines the bean properties with db data. However when I update the db the data I receive in my bean is not updated. The query in db is like this: private static final String JPQL_FIND_BY_ID = "SELECT c FROM Category...

Use alternative producers of EntityManager / EMF in integration tests

java,maven,jpa,integration-testing,cdi
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...

Envers Pre/PostCollection Listener

java,hibernate,jpa,hibernate-envers
I use Hibernate Envers with conditional logging. The documentation describes quite well how this can be done (http://docs.jboss.org/hibernate/orm/4.2/devguide/en-US/html/ch15.html#d5e4449). At 2nd item, it says you have to subclass the appropriate listeners.. The purpose of the three listeners EnversPostDeleteEventListener, EnversPostInsertEventListener and EnversPostUpdateEventListener is clear to me. However, I am not quite clear...

JPA and Apache Aries: persistence unit unresolved dependency

java,jpa,osgi,blueprint-osgi,aries
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...

performance of executing openjpa query

java,performance,jpa,openjpa
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>...

Spring JPA Projection including links

java,spring,jpa,spring-data,spring-data-rest
Given a simple model of Event that has a Set of Booking objects: Event: @Entity public class Event { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Long eventId; private Date start; private Date end; private String title; @OneToMany(mappedBy="event") private Set<Booking> Bookings; protected Event() { // for JPA } // Getters and setters omitted for...

Use JSF, JPA, JTA, JAAS, CDI, Bean Validation with Tomcat? [closed]

jsf,tomcat,jpa,cdi,jta
Is it possible to use the following APIs with tomcat (as a lightweight server): JSF, JPA, JTA, JAAS, CDI, Bean Validation. ...

Cascade types in JPA

hibernate,jpa,eclipselink,cascade,jpa-2.1
Given two entities Department and Employee forming a one-to-many relationship from Department to Employee. Since the relationship is quite intuitive, I am leaving out the entity classes. In Department : @OneToMany(mappedBy = "department", fetch = FetchType.LAZY) private List<Employee> employeeList = new ArrayList<Employee>(0); In Employee : @ManyToOne(fetch = FetchType.LAZY) private Department...

Sqlite JPA Primary Key error

java,sqlite,jpa
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...

Configure HikariCP + Hibernate + GuicePersist(JPA) at Runtime

java,hibernate,jpa,hikaricp,guice-persist
I have a java8 desktop app using GuicePersist, Hibernate, and HikariCP to communicate with a Postgres DB. I've had success getting my app to send/receive data to the DB using this META-INF/persistence.xml: <?xml version="1.0" encoding="UTF-8"?> <persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0"> <!-- A JPA Persistence Unit --> <persistence-unit name="myJPAunit" transaction-type="RESOURCE_LOCAL"> <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>...

Share same JPA persistence.xml accross multiple EJB JARs inside EAR

java,jpa,weblogic
Our project has multiple EJB modules and we want to share a single persistence.xml file between them. We put the persistence.xml file inside EARs META-INF directory, but the persistence unit is not available at runtime. It seems like the file is never read since we forced incorrect classes and jar...

How to know an object has changed compared to database

java,hibernate,jpa,playframework,playframework-1.x
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...

Preventing infinite recursion in JAX-RS on JPA Entity Serialization (JSON) (without using Jackson annotations)

java,jpa,jackson,jax-rs,resteasy
I have an Entity as follows: @XmlRootElement @Entity @Table(name="CATEGORY") @Access(AccessType.FIELD) @Cacheable @NamedQueries({ @NamedQuery(name="category.countAllDeleted", query="SELECT COUNT(c) FROM Category c WHERE c.deletionTimestamp IS NOT NULL"), @NamedQuery(name="category.findAllNonDeleted", query="SELECT c from Category c WHERE c.deletionTimestamp IS NULL"), @NamedQuery(name="category.findByCategoryName", query="SELECT c FROM Category c JOIN c.descriptions cd WHERE LOWER(TRIM(cd.name)) LIKE ?1") }) public class Category...

How to Fetch Data using Spring Data

spring,jpa,spring-boot,spring-data
Hey i want to create a repository extending JpaRepository and fetch result without writing actual query, In my example i have 2 tables Book and Author mapped by many to many relationship, suppose i want to fetch list of books by a particular author_id, since in my book entity, i...