FAQ Database Discussion Community


Defining Transient Pojo (Object) Fields in Hibernate

hibernate
I have an entity for hibernate orm like below. In this entity, i dont want to persist EntHesaplasma object. so i used @transient annotation. import javax.persistence.Transient; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "CARI_HAREKETLERI") public class EntCariHareketler { private Integer cha_RECno; @Resolvable()...

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

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

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 =...

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 })...

unable to pass two lits to the jsp using apachi tiles

hibernate,jsp,spring-mvc,tiles
i am using spring mvc with Apache tile and hibernate.i pass tow lists to the jsp page.but it is print by but there's no any thing prints. my controller class as follows : if(userExists!=0){ model.addAttribute("Maintabs",new Maintab()); model.addAttribute("MaintabsList",loginService.listMaintabs()); model.addAttribute("Subtabs",new Subtab()); model.addAttribute("SubtabsList",loginService.listSubtab(userExists)); return "redirect:/Loginsucess"; }else{ model.addAttribute("error", "ERROR : invaliduser !,Please Try Again!");...

How to convert Hibernate List to String?

java,string,hibernate,list,hibernate-criteria
The method below opens the session, executes hql and returns a string list properly. I would like to return a "String" result instead of a List. public List<String> getStates() throws Exception { try { Session session = sessionFactory.openSession(); return session.createQuery("from States").list(); } catch(Exception e) { //Logging } finally { if(session...

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

Hibernate Primary Key annotation returns null value

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

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 /...

Spring Boot extending CrudRepository

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

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

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

NullPointerError on saveOrUpdate Hibernate

java,spring,hibernate
I am trying to update an object in this function: public void priceLot(long lotId) throws Exception { Lot lot = this.getLotById(lotId); List list = bookService.getBooksByLotNumber(lotId); Book book = new Book(); ProductAvailability pa = null; float retail = 0; for(int i = 0; i < list.size(); i++) { book = (Book)...

Why does Spring Data JPA + Hibernate generate incorrect SQL?

java,spring,hibernate,spring-data-jpa
I have two entities with a one-to-many relationship. I want to get all entities that are tied to a set of the other entity. This are my classes: public class Instance { @Id @GeneratedValue private long id; @OneToMany(mappedBy = "instance") private Set<Action> actions = new HashSet<>(); } public class Action...

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

java,spring,hibernate,spring-mvc,dto
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...

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

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

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)...

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

Set LocalDateTime to autogenerate with hibernate 4.3.10

java,hibernate,time
Currently I have a base entity as follows: @MappedSuperclass public abstract class BaseEntity { @Id @GeneratedValue(strategy=GenerationType.SEQUENCE) private Long id; private boolean deleted; @Convert(converter = LocalDateTimePersistenceConverter.class) private LocalDateTime createdAt; @Convert(converter = LocalDateTimePersistenceConverter.class) private LocalDateTime updatedAt; } Is it possible to annotate LocalDateTime with something to make database default to current date...

org.hibernate.MappingException: Repeated column in mapping for entity

java,hibernate
I have two Domain-Models: "UserBean" and "LoginBean". It's a one-to-many relationship, an user has many record of login. LoginBean.userid is foreign key of UserBean.id . Here are DDL of database: CREATE TABLE `users` ( `id` int(11) NOT NULL, `username` varchar(255) DEFAULT NULL, `password` varchar(255) DEFAULT NULL, `register_date` datetime DEFAULT NULL,...

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 Search not indexing items from database

java,spring,hibernate,lucene,hibernate-search
I'm trying to integrate Hibernate Search in my application. Rough summary of what needs to be done: Spring Batch reads out an XML file and persists the objects to database. This is done with de JDBCBatchItemWriter. Not the HibernateItemWriter because of slow performance. After all items are inserted I would...

Comparing 2 dates javafx

java,hibernate,date,javafx,javafx-2
I'm writing an application which is based on javafx/hibernate. Now i have problem when i want to make new table with articles that are sold last 7/30/365 days (or custom date chosen). articles are stored in database with current date (Date articleDate = new Date(); ) all articles are fetched...

Not able to typecast from object to class:

java,spring,hibernate
I am not able to typecast from object variable to class type variable. Getting following error: *Hibernate: select osinfo0_.host_id as host_id1_17_0_, osinfo0_.os_build as os_build2_17_0_, osinfo0_.os_name as os_name3_17_0_, osinfo0_.os_type as os_type4_17_0_, osinfo0_.os_version as os_versi5_17_0_ from hwi.os_info osinfo0_ where osinfo0_.host_id=? Jun 15, 2015 10:28:20 AM org.apache.catalina.core.StandardWrapperValve invoke SEVERE: Servlet.service() for servlet [spring]...

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

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

Hibernate does't update joined collection

hibernate,orm
I have an Employee entity (employee(id,name,company_id)): @Entity public class Employee { @Id @Column(name="ID") private Integer id; @ManyToOne(fetch = FetchType.EAGER, cascade=CascadeType.ALL) @JoinColumn(name = "COMPANY_ID") private Company company; ... } and I have a Company entity (company(id,name)): @Entity public class Company { @Id @Column(name="ID") private Integer id; @OneToMany(fetch=FetchType.EAGER, cascade=CascadeType.ALL) @JoinColumn(name="COMPANY_ID") @Where(clause="status_code =...

Can't Override Equals method on Java when calling contains

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

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

How to delete multiple rows in Hibernate

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

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

to generate a table with list using hbm file

java,hibernate,arraylist
I am new to Hibernate and trying to make an insertion of ArrayList<String> in DB using .hbm mapping file. I want no annotations to use. I made a search on how to insert ArrayList<String> and found working code from here. I was expecting that a new table containing entries of...

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 Boot - How to set the default schema for PostgreSQL?

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

Hibernate delete child when parent is getting updated in same transaction

hibernate,spring-data
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();...

What is the equivalent HQL query for this SQL query (fetch max value from Inner Join)

sql,hibernate,hql
I've worked my way to this SQL query (tested and working as expected): SELECT c.carId, p.color as currentColor FROM Car c Inner join Paint p ON( p.PaintId In (Select max(p2.PaintId) From Paint p2 where p2.carId = c.carId) ) What is the equivalent HQL query ? (Suppose that Class names and...

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

Hibernate Lazy loading not work in OneToOne relation

hibernate,java-ee
In my company we migrated one old app from Hibernate 2 to Hibernate 4. My task was to move all xml entities to annotations. After moving it lazy loading in OneToOne relationship stop working. entity a xml: <id name="entityAid" type="integer" column="entityAid_id"> <one-to-one name="entityB" entity-name="EntityB" property-ref="entityA" /> entity b xml: <property...

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"...

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

hibernate
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...

How to call MySQL view in Struts2 or Hibernate

java,mysql,hibernate,java-ee,struts2
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...

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

HQL order by expression

java,sql,database,hibernate,hql
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...

Spring + Hibernate + Quartz: Dynamic Job

java,spring,hibernate,quartz-scheduler
I want to create dynamically jobs using Quartz, Spring and Hibernate. Users interact with a web service to create jobs of this class: public class StartJobSpring extends QuartzJobBean { private String jobId; private String jobType; @Autowired private NoaJobInstancesDAO njiDAO; @Transactional @Override protected void executeInternal(JobExecutionContext context) throws JobExecutionException { JobKey key...

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

could not resolve property: userId.username

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

How to get row count after JOIN in Hibernate Criteria?

java,mysql,hibernate,criteria
I try to create request: Criteria criteria = session.createCriteia(User.class); criteria.setFetchMode(field, FetchMode.JOIN); int count1 = criteria.list().size(); //340 Number count2 = (Number) criteria.setProjection(Projections.rowCount()).uniqueResult(); //279 How to return 340 without calling criteria.list().size() ?...

Quickest way to retrieve information from database

java,spring,hibernate,loops,for-loop
I am trying to resolve a problem which i am currently facing. I am trying to find out which is the fastest way to retrieve information from a database. So a managers name is passed in, what i need to do is return all the users who's manager is passed...

Hibernate Domain Object Generation

java,mysql,hibernate,code-generation
I'm trying to understand how to best generate and synchronize domain model POJO's from my database using Hibernate. Right now the process I managed to build is the following: Build the ER schema on the database Have an hibernate.reveng.xml file containing the elements (one for each table) Use JBoss tools...

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

Bean property xxxDAO is not writable or has an invalid setter method

java,xml,spring,hibernate,spring-mvc
I know this question has been asked many times. But I could not find my solution. I am using spring with hibernate. There is a connection between User and UserWord as one to many mapping I have done same logic for other models and everything went OK. However when I...

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 =...

calling stored function in hibernate

spring,oracle,hibernate
I am trying to call a stored function in hibernate but I am getting invalid sql exception. Java code --- public Integer callSqlBlock(){ Integer outputValue =1; Session session = getHibernateTemplate().getSessionFactory().getCurrentSession(); session.doWork(new Work() { @Override public void execute(Connection conn) throws SQLException { CallableStatement stmt = conn.prepareCall("? = call test(?)"); stmt.registerOutParameter(1, Types.INTEGER);...

How to avoid Hibernate Validator ConstraintDeclarationException?

java,spring,hibernate,validation,hibernate-validator
I have my WebService based on Spring 4, and I am using Hibernate Validator (beyond MethodValidationPostProcessor). My problem is that I have my ClientService interface, and its implementation. So I put Bean Validation constraints on the implementation and it forces me to put that constraints on the interface (throwing ConstraintDeclarationException)...

Hibernate criteria accepting %% value

java,hibernate,java-ee,orm,hibernate-criteria
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...

fixed field in hibernate query

java,mysql,hibernate
hi i want to make a hibarnate query, but in one field i want it to be static or contant string. here's a an sql query equivalent to the hibernate query that i want to make select sum(amount),sum(sales),"info" from products for hibernate i did this but it doesn't work that...

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

How to pass parameter in HQL query

sql,hibernate,hql
find below my HQL query Query query = session.createQuery("select u from UserLog u where u.userLogSerialno = " + "(select max(uu.userLogSerialno) from UserLog uu where uu.userId = u.userId)"); This query is working fine but in this, I want to pass the value of userId but I am not able to figure...

Using Hibernate on JSP

java,hibernate,jsp
So i went to the website and downloaded hibernate release 4 and i extracted and i created a library in my eclipse and i added all the needed jars but it shows that my hibernate import is not working well.. am i importing them wrongly? any help would do. This...

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

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

Hibernate : session.get(…) vs session.getNamedQuery(…)

java,hibernate,dao,hibernate-session
In the a transaction process I create/save an object and next to end of transaction I read again object (before setting an history event) @org.springframework.stereotype.Service @Transactional(value="transactionManager") public class UTServiceImpl implements UTService { private static final Logger logger = Logger.getLogger(UTServiceImpl.class); ... @Autowired private DeclarationDao declarationDao; ... public Integer ajouterPersonneImpliquee(ContexteService contexte, Integer...

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

java,hibernate,jersey,jax-rs
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...

unexpected token : ( subquery hql

sql,hibernate,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))...

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 ?...

Unable to connect to database after migrating to Hibernate 4

java,spring,hibernate,database-connection,c3p0
I am trying to update hibernate from 3.6.10.Final to 4.3.6.Final. With 3.6.10 everything worked fine. I renamed the changed classes to the new classnames and get no errors on that side, but when I run the webapplication I get an error: 2015-06-12 10:44:35.345 ERROR SchemaUpdate:201 - HHH000319: Could not get...

Hibernate - org.hibernate.QueryException: could not resolve property:

java,hibernate,criteria,many-to-one
I have a class DocMovement like this : @Entity @Table(name = "DOC_MVMNT") public class DocMovement { @Id @GeneratedValue @Column(name = "MVMNT_ID") private int mvmnt_id; @ManyToOne @JoinColumn(name = "BARCODE") public DocMaster docMaster; // other fields and getters setters } The DocMaster class is something like this : @Entity @Table(name="DOC_MASTER") public class...

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

what is gradle missing to map hibernate?

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

Unidirection OnetoOne mapping foreign primary key is not generating in child table

java,hibernate,hibernate-mapping,one-to-one,hbmxml
I have one parent table CUSTOMER_ACCOUNT and one child table CUSTOMER_TEMPINFO. I'm trying to generate the primary key in parent table and assign the same in child table. I've to use the unidirectional way, so bidirectional solution please until absolutely necessary. Is there something wrong in the association order! Need...

How to get some utf-8 characters using hibernate and spring mvc in database?

java,spring,hibernate,spring-mvc,tomcat
I have developed small server program. When I extract tuple from database, some characters become ÇѱÛÃàÁ¦. I modify server.xml. However ÇѱÛÃàÁ¦ characters still appear. Help me. How can I get correct characters? This is my server.xml. (I use apache tomcat 7.0 server.) <?xml version="1.0" encoding="UTF-8"?> <!-- Licensed to the Apache...

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

JPA2 get column metadata (type, lenth, nullable, etc)

hibernate,jpa-2.0
title says it all, I'm working on a JPA2 (through Hibernate 4.0) based data layer that needs to be database agnostic, and I'm trying to retreive whether a column of a table (associated with an @Entity) is nullable, what the type is, and most importantly, if it's a varchar, how...

Bean Creation exception, Injection of autowired dependency failed

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

hibernate rollback not working in service layer

hibernate,postgresql,transactions,junit4,spring-4
i have issue in rollback insert/update data in postgresql database, in service layer, where as in DAO layer it is working fine. My DAO junit test Code @ContextConfiguration("classpath:datasource-context-test.xml") @RunWith(SpringJUnit4ClassRunner.class) @TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true) @Transactional public class SellerDAOTest { @Test @Rollback(true) public void testAddSeller() { try { SellerDO sellerDO...

Hibernate dynamic entity model

java,hibernate
I am creating a Java application that utilizes a JPA annotated model - the core model -. On top of these entities, at runtime, I would like to add a jar file from an external source that contains some other JPA classes definitions and mappings. The imported archive might change...

i am passing a model class object but it print ad normal object

hibernate,spring-mvc,jstl
i am passing hibernate model class object type list but it prints as [Ljava.lang.Object;@1ec3adc.i am using spring mvc and tile hibernate.i want to pass "Subtab" type list.but it's passing "object" type list. here's the code for returning the list : DAOImpl : public List<Subtab> listSubtab(int usertype){ List<Subtab> subtablist=sessionFactory.getCurrentSession().createQuery("SELECT s.maintab, s.description,...

Java Hibernate Hierachy Different JoinColumn in Child class Column 'C01' specified twice

java,mysql,hibernate
I have severals Entitys in my models but some of them share a same property namely Student i have created a abstract class like this. @javax.persistence.MappedSuperclass public abstract class StudentImpl { private Student student; @ManyToOne(fetch=FetchType.LAZY)@JoinColumn(name="c01") public Student getStudent(){return student;} @Override public void setStudent(final Student student){this.student=student;return;} } this is working like...

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

how to return two lists from controller class in spring mvc

java,hibernate,jsp,spring-mvc,tiles
I have two tables call maintab,subtab for generate menubar. maintab has maitabId ,main_tab_name subtab has: sub_tb_ID ,main_tb_id,subtab_name ,Url I want to get two list containig list1=maintabid & maintabname list2=subtabname,maintabID & url I want to return the two list using spring mvc. And retrieve in jsp page to populate a menu.Please...

erroneous with SQLite3 query in Java

java,hibernate,jdbc,sqlite3
I am parsing data out of a metrolink database. When I query the db from the command line I get the following out put : Stop Name Latitude Longitude ---------------------------------------- --------------- CLAYTON METROLINK STATION 38.645657 -90.339223 SUNNEN METROLINK STATION 38.607509 -90.330296 MAPLEWOOD METROLINK STATION 38.614023 -90.331314 BRENTWOOD METROLINK STATION 38.627851...

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

How can implement long running process in spring hibernate?

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

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

DTOs with different granularity

java,spring,hibernate,design-patterns,dto
I'm on a project that uses the latest Spring+Hibernate for persistence and for implementing a REST API. The different tables in the database contain lots of records which are in turn pretty big as well. So, I've created a lot of DAOs to retrieve different levels of detail and their...

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

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;...

Hibernate - Setting null in entity collection is automatically persisted at transaction commit

java,spring,hibernate,dozer
Due to architecture requirements we can't use our Hibernate entities as DTOs, so we use Dozer to transform those entities to POJOs. Our typical service looks like this: @Transactional(readOnly=true) @Override public Task loadTask(int taskId){ TaskEntity taskE = taskDAO.load(taskId); if (taskE != null){ taskE.setAttachments(null) Task task = objectMapper.convert(taskE, Task.class); return task;...

Spring and Tomcat: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set

java,mysql,spring,hibernate,tomcat
I have an application that uses the Spring Repository framework and a MySQL database. I currently have it deployed on Tomcat 7. Once I deploy and attempt to log into the application (the first call to the database) I receive the following exception: SEVERE: Exception sending context initialized event to...

Unable to get correct session factory

spring,hibernate
I am using hibernate along side spring to configure the session factory and hibernate transaction manager, below mentioned is the apllication-context file--- <?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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"...

Using like to non-string columns in Grails

hibernate,grails,gorm
I'm currenty working on a Grails query service that involves retrieving row/s from the database with a specific criteria called filterText. List getAdjustmentCodes(params) { def filterText = params.filterText . . . adjustmentCodeList = AdjustmentCode.findAll{ or { ilike('description', "%$filterText%") // ilike('id', "%$filterText%") } } return adjustmentCodeList } Notice that I've comment...

Why is my Set variable throwing error when doing a many-many query?

java,spring,hibernate,jsp,spring-mvc
I am new to spring and hibernate. I have created a spring-mvc app with hibernate integration and when I run the code I get the below error. My requirement is to pick the relevant path from the advertisement given the customer category. This involves two tables respectively along with the...

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

Hibernate without entities

hibernate
because of some reasons we have to call stored procedure from hibernate without creating entities, is it even possible to attain this? If yes some bread crumbs are required to achieve this. So in short --- Problem statement If we are not using entities to map database table via hbm...

How to write a custom CrudRepository method(@Query) to filter the result in my case

java,mysql,spring,hibernate,spring-data-jpa
I am new to Spring JPA and Repository stuff. I have an Auction class with a bunch of fields in it, and one of the field is category. I want a custom method in CrudRepository to filter the results by Category.name; @XmlRootElement @Entity(name="AUCTION") public class Auction implements Serializable{ private static...

Is it possible to add Stored procedure dynamically from hibernate?

java,mysql,sql,hibernate,stored-procedures
I want to add stored procedures dynamically from my Java code using hibernate. I did the following but this constantly results in error saying " You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use what...

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

Hibernate : Stale state exception

java,spring,hibernate,spring-mvc,transactions
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...