Menu
  • HOME
  • TAGS

could not resolve property: userId.username

java,hibernate,criteria

Criteria does not work like EL or Java methods or attributes, you cannot refer to inner objects with a dot .. You have to create a restriction in Ticket, right? What does Ticket has? An User. Then... you have to create a new User, set the username to this User...

JPA NamedNativeQuery syntax error with Hibernate, PostgreSQL 9

java,hibernate,postgresql,jpa

So the problem was that em.createNativeQuery(...) was not the correct invocation of a NamedNativeQuery in order to do that I should've invoked em.createNamedQuery(...). However, seeing that em.createNativeQuery(...) does not accept @SqlResultSetMapping it is very difficult to map the result to a custom class. The end solution was to use return...

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

java,oracle,hibernate

Have you tried the solutions in the following question? Oracle 11g connection reset error One particular answer had to do with the following comment: I could get it resolved by adding this parameter to the Hotspot JVM: -Djava.security.egd=file:/dev/./urandom This issue does not affect windows, so it might be similar to...

Hibernate @OneToOne child not persisting

java,spring,hibernate,jpa,spring-roo

Try this on StockProperty: @OneToOne(cascade = CascadeType.ALL) @JoinColumn(name = "idStock", nullable = false) private Stock stock; And this on Stock: @OneToOne(mappedBy="stock") private StockProperty stockProperty; ...

Hibernate Search not indexing items from database

java,spring,hibernate,lucene,hibernate-search

I think the problem is that you defining your Search properties in jpaProperties which is processed by the entity manager. When you call the mass indexer, however, you are using a plain Session. In this case the JPA properties will not be picked up. My guess is that there is...

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

java,hibernate,dao,hibernate-session

You are using sessionFactory.getCurrentSession() which gives you a Spring managed session bean back. Ordinarily you would get an exception (no active transaction), but you don't cause you have placed @Transactional on your UIService so it wraps the whole ajouterPersonneImpliquee() method into one transaction. The flush time is depended on the...

fixed field in hibernate query

java,mysql,hibernate

Just do the same thing as in SQL. But don't use a named parameter to pass the constant. Embed it in the query: session.createquery("select sum(amount), sum(sales), 'information' from Products").list() I fail to see the point of selecting a constant value, though....

Spring + Hibernate + Quartz: Dynamic Job

java,spring,hibernate,quartz-scheduler

SHORT SOLUTION: let Spring make your jobs through factories. LONG SOLUTION: here the long description. I have modified my configuration file by importing an xml configuration file: <bean name="complexJobDetail" class="org.springframework.scheduling.quartz.JobDetailFactoryBean"> <property name="jobClass" value="jobs.StartJob" /> <property name="durability" value="true" /> </bean> <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean"> <property name="jobDetail"...

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

java,hibernate,jpa

Yes, there is a schema generator class. org.hibernate.tool.hbm2ddl.SchemaExport Here's a sample code on how I use it (note that this was very highly inspired from a post here) package com.mypackage.jpa.util; import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.List; import org.hibernate.cfg.Configuration; import org.hibernate.tool.hbm2ddl.SchemaExport; public class SchemaGenerator { private Configuration cfg; public...

Hibernate without entities

hibernate

You can use your own SQL to insert, update, delete and even select data from the database. But there are clear expectations to the arguments. <class name="Person"> <id name="id"> <generator class="increment"/> </id> <property name="name" not-null="true"/> <sql-insert>exec createPerson ?, ?</sql-insert> <sql-delete>exec deletePerson ?</sql-delete> <sql-update>exec updatePerson ?, ?</sql-update> </class> See the reference...

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

java,spring,hibernate,spring-mvc,tomcat

first remove this line <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> and this add into header tag <meta http-equiv='Content-Type' content='text/html; charset=UTF-8' /> then add into web.xml <filter> <filter-name>encoding-filter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value>...

How to call MySQL view in Struts2 or Hibernate

java,mysql,hibernate,java-ee,struts2

You can simply create an Entity, that's mapping the database view: @Entity public class CustInfo { private String custMobile; private String profession; private String companyName; private Double annualIncome; } Make sure you include an @Id in your view as well, if that's an updatable view. Then you can simply use...

erroneous with SQLite3 query in Java

java,hibernate,jdbc,sqlite3

You are using metroData.setStopDesc() to store the latitude, instead of the setter for latitude.

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

java,hibernate,jpa,ejb

So it looks like this class (and a lot of the other EJB stuff) has been renamed and moved around. I was able to replace instances of org.hibernate.ejb.event.EJB3MergeEventListener (which was located in the hibernate-entitymanager jar in version 3.6.10) with org.hibernate.event.internal.DefaultMergeEventListener (which is actually located in the hibernate-core jar in version...

Hibernate dynamic entity model

java,hibernate

I managed to solve the problem. The main point is that, when using EntityManagerFactory (the JPA API), the hibernate persistence provider only reads the persistence.xml configuration files and loads the persistence units that are specified therein. However, using a hibernate API configuration, hibernate does not read the persistence.xml files, so...

hibernate rollback not working in service layer

hibernate,postgresql,transactions,junit4,spring-4

Using REQUIRES_NEW will run your code in a new transaction separately from the one that JUnit creates. So you are creating a nested transaction by invoking your service layer code. Change Propagation.REQUIRES_NEW to Propagation.REQUIRED in your service layer. Also since Propagation.REQUIRED is the default propagation level, you can remove this...

Bidirectional relationships in JPA

hibernate,jpa,eclipselink,jpa-2.1,bidirectional-relation

What this means is that with your particular example, if you change the code to add the employee to the department (and not the other way of setting the department) then you will notice that this will not automatically set the department on the employee. You will have to write...

How to convert Hibernate List to String?

java,string,hibernate,list,hibernate-criteria

You can simply use a String, iterate throught your list elements and append them to this String: Session session = sessionFactory.openSession(); Query q = session.createQuery("from States"); List<String> list = (List<String>) q.list(); String listAsString = ""; for (String str : list) { listAsString += str + "\n"; } return listAsString; You...

Hibernate's ManyToMany simple use

java,spring,hibernate,jpa,many-to-many

Change many to many mapping in CollabEntity. You need to change join table name. i.e. name from technos to some other name. @ManyToMany(cascade = CascadeType.ALL) @JoinTable(name = "collab_technos", joinColumns = {@JoinColumn(name = "co_id", nullable = false, updatable = false)}, inverseJoinColumns = @JoinColumn(name = "te_id") ) ...

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

hibernate,jpa,eclipselink,bean-validation,jsr303

It looks like the version isn't actually set until the entity is modified, therefore rowVersion is null when the entity is first created. That fails your "not null" check. Try this instead and see if it works: @Version @Basic(optional = false) @NotNull @Column(name = "row_version", nullable = false) private Long...

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

java,hibernate,jersey,jax-rs

In this case we generally send a 404. The URL is the identifier for the resource. If part of the URL is used as an identifier for determining the resource, then the appropriate reply for a resource not being found by that identifier, is a 404 Not Found. Generally, personally...

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

hibernate

No, there is no such feature in Hibernate.

what is gradle missing to map hibernate?

java,hibernate,gradle

I think the problem is not really with gradle. It's with the fact that the JPA spec stupidly requires that the classes of the entities are in the same jar/directory as the persistence.xml file. And since Gradle doesn't store the "compiled" resources in the same output directory as the compiled...

Unable to connect to database after migrating to Hibernate 4

java,spring,hibernate,database-connection,c3p0

You need to remove the following properties: <prop key="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider <prop key="hibernate.c3p0.min_size">3</prop> <prop key="hibernate.c3p0.max_size">50</prop> <prop key="hibernate.c3p0.timeout">1800</prop> <prop key="hibernate.c3p0.idle_test_period">100</prop> Hibernate already uses the external dataSource so it doesn't use the internal ConnectionProvider mechanism. You are getting an exception, because...

very high float value changing to infinity while retrieving from database

java,mysql,sql-server,hibernate,jpa

You should use double instead of float: // Float.MAX_VALUE = 3.4028234663852886E38f float f = Float.parseFloat("1.11111111111111E+49"); System.out.println("f=" + f); // -> f=Infinity // Double.MAX_VALUE = 1.7976931348623157E308 double d = Double.parseDouble("1.11111111111111E+49"); System.out.println("d=" + d); // -> d=1.11111111111111E49 ...

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

sql,hibernate,hql

Since it is an inner join and you do not use p2 in the select clause, you can move the subquery to the where clause. SELECT c.carId, s.color as currentColor FROM Car c, Paint p WHERE p.PaintId In ( Select max(p2.PaintId) From Paint p2 where p2.carId = c.carId) (by the...

Checking for multiple child constraint violations in Hibernate/JPA

spring,hibernate,jpa

I found a way to accomplish my end result, although it was through means I did not expect. In order to accomplish my goal, I would need to use nested transactions and SavePoints. At the end of the day, that implementation would still produce invalid data in my database, because...

Unable to get correct session factory

spring,hibernate

So what you're saying is that getHibernateTemplate() returns a template with the wrong session factory? You're creating 2 session factories but not explicitly stating which one gets assigned to the EventDAOImpl instance. @DependsOn only states that the object will be created by Spring after the ecommSessionFactory, that does not mean...

How to get row count after JOIN in Hibernate Criteria?

java,mysql,hibernate,criteria

I think while using Projections.rowCount() hibernate ignores criteria.setFetchMode(field, FetchMode.JOIN); You can use createAlias criteria.createAlias("field","field", JoinType.LEFT_OUTER_JOIN); Check query generated by hibernate in both the cases by using hibernate.show_sql in Hibernate configuration file https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/session-configuration.html#configuration-optional...

How to know an object has changed compared to database

java,hibernate,jpa,playframework,playframework-1.x

To force Hibernate to start a new transaction in the playframework and thus give you a new entity manager that will return the object as it is in the database and not a reference to it, you need to specifically ask the play framework to start a new transaction through...

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

java,spring,hibernate,jpa,spring-data

You should add property mitfac to xxx.Mitmas class.

Not persisted entity with Hibernate

java,spring,hibernate,jpa

upd Answer, corresponding to the first version of a question was entirely removed - in short, it suggested to flush changes again after entity was updated. Current problem is in mixing two kinds of annotation - first is @ManyToOne annotation that belongs to JPA specification and second is @Cascade that...

Comparing 2 dates javafx

java,hibernate,date,javafx,javafx-2

On mkyong there are 3 possibilities in comparing Date in Java. In the comment section even the better choice (IF Javaversion < 8) of Joda-Time is presented. The simpliest Solution without Joda would probably be just to compare using Calendar: Calendar articleCal = Calendar.getInstance(); articleCal.setTime(articleDate); //check for past 7 days...

HQL order by expression

java,sql,database,hibernate,hql

HQL doesn't support such a syntax, so you'll have to use a native query for this: List<Comment> comments = (List<Comment>) session.createSQLQuery( "select * " + "from Comment " + "where id in ( " + " select comment_id " + " from ( " + " select " + "...

Hibernate does't update joined collection

hibernate,orm

First, your employeeSet mapping is wrong. Change it to @OneToMany(fetch=FetchType.EAGER, cascade=CascadeType.ALL, mappedBy = "company") @Where(clause="status_code = '1'") private Set<Employee> employeeSet; Second, you need to handle the other side of the relation as well, meaning you need to add the employee to the new company's employeeSet and remove it from the...

Hibernate criteria accepting %% value

java,hibernate,java-ee,orm,hibernate-criteria

Hibernate does not escape special chars in like (e.g. the percentage % sign). But there are descriptions how to solve it (escape it): Escaping special characters in Hibernate queries Using hibernate criteria, is there a way to escape special characters? Escape special characters in hibernate criteria In general we could...

Quickest way to retrieve information from database

java,spring,hibernate,loops,for-loop

What you need is to perform a performance analysis, in order to know if the latency comes from the database, the application server, or the network (latency due to many loops). According to your figures, I think you are doing too many queries, but this is an hypothesis you should...

JPA annotation for MS SQL Server 2008 R2 IDENTITY column

hibernate,sql-server-2008,jpa,spring-data-jpa

I just found I missed setting up hibernate dialect on LocalContainerEntityManagerFactoryBean. After setting up org.hibernate.dialect.SQLServer2008Dialect as hibernate dialect, the GenerationType.IDENTITY works fine as Neil mentioned. Below is my spring data configuration and application.properties. FYI I have multiple datasource, one is H2 embedded datasource for internal use and the other is...

Using Hibernate on JSP

java,hibernate,jsp

To me it seems like something is missing , Not that an expert of JSP, but I see that you don't import stuff around the hibernate package. You do seem to import "java.util.*" - but what about the hibernate packages? Where do you import them? In addition, do you see...

Hibernate Lazy loading not work in OneToOne relation

hibernate,java-ee

What work for mi is Lazy one-to-one inverse relationships. I read about this here (it is also a good tutorial how to use it). I hope it will help some one as it helps me....

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

java,mysql,spring,hibernate,spring-data-jpa

You need to add @Param annotation to the method variable name so that you can refer it in your query. Code you have written is absolutely fine. In case you need access to EntityManager, then you will need a custom repository. @Query("from Auction a join a.category c where c.name=:categoryName") public...

Is possible do not fetch eager relation in JPA?

hibernate,jpa

I am not sure on this, Try specifying the fetch type explicitly in your query, some thing like this: Criteria crit = session.createCriteria(ParentClass.class); crit.add(Restrictions.eq("id", id)); crit.setFetchMode("childProperty", FetchMode.LAZY); ...

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

java,spring,hibernate,jsp,spring-mvc

EDIT: In order to have a Many-to-Many mapping between the two entities you have to specify this mapping in the two sides of the relation, and that's what you are missing here because you haven't declared a collection of CustomerCategory in your Advertisement class so you have to add it,...

Configure HikariCP + Hibernate + GuicePersist(JPA) at Runtime

java,hibernate,jpa,hikaricp,guice-persist

Try removing the persistence-unit name from the JPA properties, so instead of: Map<String, String> properties = new HashMap<>(); properties.put("myJPAunit.hibernate.hikari.dataSource.url", "jdbc:postgresql://192.168.100.75:5432/mpDb"); properties.put( + "myJPAunit.hibernate.hikari.dataSource.user", "cowboy"); properties.put( + "myJPAunit.hibernate.hikari.dataSource.password", "bebop"); you should have this: Map<String, String> properties = new HashMap<>(); properties.put("hibernate.hikari.dataSource.url",...

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

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

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

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

java,spring,hibernate,jpa,transactions

The problem is due to this property: <prop key="hibernate.transaction.jta.platform">ch.vd.dsas.rdu.ref.transaction.jencks.JencksTransactionManagerLookup</prop> The hibernate.transaction.jta.platform property is not the same with hibernate.transaction.manager_lookup_class and it should point to an AbstractJtaPlatform implementation: <property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.SunOneJtaPlatform"/> ...

Hibernate Primary Key annotation returns null value

sql,spring,hibernate

Your mapping says that the ID of profile is also a join column (i.e. a foreign key referencing the user ID). That's what @PrimiryKeyJoinColumn means. But your table definition shows that you have a userId column in profile to reference the profile's user ID. So you should in fact use...

Blocking Updating or Inserting an Entity when using Cascade in Hibernate

java,hibernate,jpa,orm,hibernate-mapping

If you never want to modify the EntCariHareketler, you could simply annotate it with @Immutable. If you the entity is mutable but you want to disable updates from the other side, you need to set to false the insertable and updatable @JoinColumn attribute: @OneToOne(fetch= FetchType.LAZY) @JoinColumn(name="carihareketid", insertable = false,...

Spring Boot extending CrudRepository

java,spring,hibernate,spring-boot,spring-data-jpa

There are lots of ways you could probably accomplish this. If you really need absolute control try this interface FoobarRepositoryCustom{ List<Foobar> findFoobarsByDate(Date date); } interface FoobarRepository extends CrudRepository<Foobar, Long>, FoobarRepositoryCustom public FoobarRespoitoryImpl implements FoobarRepositoryCustom{ @PersistenceContext private EntityManager em; public List<Foobar> findFoobarsByDate(Date date) { String sql = "select fb from Foobar...

JPA persit creates new existing entity in many to one relation

java,hibernate,jpa,insert

With merge you should be using: Entity entity=entityManager.merge(newEntity); int lastId=entity.getId(); to get the reference to the object and get its id where has persist does not need to because the entity is already managed after persist....

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

java,mysql,spring,hibernate,tomcat

I was able to resolve this issue by working through the steps listed in @Soheil 's answer found here: Solving a "communications link failure" with JDBC and MySQL It turns out that all I needed was add the hibernate dialect, as @Dhanush Gopinath suggested, and add the following to my...

Hibernate : Stale state exception

java,spring,hibernate,spring-mvc,transactions

The reason for the exception is that you were loading a GroupCanvas before and this has a reference to the GroupSection. Then you delete the GroupSection but when the transaction commits GroupCanvas still holds a reference to the deleted GroupSection and you get the StaleStateException. As you saw, deleting the...

how to return two lists from controller class in spring mvc

java,hibernate,jsp,spring-mvc,tiles

Why do you want to return only a list, use map instead. In your controller you can use, Map mp = new HashMap(); mp.put("list1", lst1); mp.put("list2", lst2); return mp; in your jsp, you can iterate the map, for (Map.Entry<> entry : mp.entrySet()) { String listKey = entry.getKey(); List<> childLst =...

Can't Override Equals method on Java when calling contains

java,spring,hibernate

You need to provide an complmentary hashCode() method whenever providing an equals() method and visa-versa. The reason for this is to fulfil the API contracts when interacting with the objects in collections. See the site for tips on creating the code hashcode-equals The Java Docs have more information about the...

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

mongodb,hibernate,jpa,hibernate-ogm

The problem is with the java jar version of the mongodb as 3.x version is not yet supported have to use 2.x version of it https://forum.hibernate.org/viewtopic.php?f=31&t=1040127&p=2485319#p2485319...

How can implement long running process in spring hibernate?

java,spring,hibernate

I recommend you to use DeferredResult of Spring. It´s a Future implementation, that use the http long poling technique. http://docs.spring.io/spring-framework/docs/3.2.0.BUILD-SNAPSHOT/api/org/springframework/web/context/request/async/DeferredResult.html So let´s says that you will make a request, and the server it will return you the deferredResult, and then your request will keep it open until the internal process(Hibernate)...

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

spring,hibernate,jpa,left-join,spring-data

I have changed as following @ManyToOne(fetch = FetchType.LAZY) @JoinColumns({ @JoinColumn(updatable=false,insertable=false,name="obcono",referencedColumnName="mmcono"), @JoinColumn(updatable=false,insertable=false,name="obitno",referencedColumnName="mmitno") }) private Mitmas mitmas ; @ManyToOne(fetch = FetchType.LAZY) @JoinColumns({ @JoinColumn(updatable=false,insertable=false,name="obcono",referencedColumnName="m9cono"), @JoinColumn(updatable=false,insertable=false,name="obitno",referencedColumnName="m9itno"),...

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

java,hibernate,hibernate-mapping,one-to-one,hbmxml

Unfortunately you must specify from which associated entity you want to get the ID value, through the required property property to initialize the foreign generator. So you need to add at least the association from child to parent. Something like this: <hibernate-mapping> <class name="com.rup.example.po.CustomerTempInfo" table="CUSTOMER_TEMPINFO"> <id name="customerId" type="int" column="customer_id"> <generator...

Why does Spring Data JPA + Hibernate generate incorrect SQL?

java,spring,hibernate,spring-data-jpa

According to the Spring Data spec you have to define this method as: List<Instance> findByActionsIn(Collection<Action> actions); ...

Bean Creation exception, Injection of autowired dependency failed

java,spring,hibernate,spring-mvc

As you can see in the stacktrace: nested exception is java.lang.NoClassDefFoundError: org/apache/commons/pool/impl/GenericObjectPool The class GenericObjectPool is missing in your classpath. So you have to add the commons-pool.jar to your project which contains this class....

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

java,spring,hibernate,spring-mvc,dto

What I think that happens is Jackson tries to serialize all fields in the hierarchy based on getter methods. In some situation NullPointerException is thrown in the following method: @JsonIgnore public int getOwnedSectionId(){ return this.ownednotes.getMsectionid(); } replace it with the following method: @JsonIgnore public int getOwnedSectionId(){ if(this.ownednotes != null) return...

calling stored function in hibernate

spring,oracle,hibernate

You can either change the prepareCallline to use the JDBC escape syntax by enclosing the call in braces, as in CallableStatement stmt = conn.prepareCall("{? = call test(?)}"); or you can use a PL/SQL block in the call, such as CallableStatement stmt = conn.prepareCall("begin ? := test(?); end;"); The JDBC syntax...

How to avoid Hibernate Validator ConstraintDeclarationException?

java,spring,hibernate,validation,hibernate-validator

To answer your first question. The behavior is specified in the Bean Validation specification section 4.5.5. Method constraints in inheritance hierarchies. Basically the rule is that a method's preconditions (as represented by parameter constraints) must not be strengthened in sub types. This is the so called Liskov substitution principle. To...

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

hibernate,spring-mvc,jstl

Please go through the Hibernate documentation: https://docs.jboss.org/hibernate/orm/3.6/reference/en-US/html/queryhql.html Queries can return multiple objects and/or properties as an array of type Object[] If you would like to return Subtab objects then change your query to SELECT s FROM Subtab s ... Also please use bind variables in your query as you will...

unexpected token : ( subquery hql

sql,hibernate,hql

Hibernate documentation states that sub-queries are allowed only in the SELECT or WHERE clause. Note that HQL subqueries can occur only in the select or where clauses. But in the example above you have a subquery in the FROM clause of the first subquery. Have you tried consolidating the 2...

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

java,hibernate,jpa

Have you tried: @JoinColumn(name = "parent_id", referencedColumnName = "id", nullable = false, insertable=false, updatable=false) ...

Cache inconsistency - Entity not always persisted in cached Collection

java,hibernate,jpa,caching,ehcache

The Hibernate Collection Cache always invalidates existing entries and both the Entity and the Collection caches are sharing the same AbstractReadWriteEhcacheAccessStrategy, so a soft-lock is acquired when updating data. Because you are using a unidirectional one-to-many association, you will end up with a Validation table and a Step_validation link table...

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

java,spring,hibernate,maven,jpa

I finally found the right combination for me: <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-annotations</artifactId> <version>3.5.0-Final</version> <exclusions> <exclusion> <artifactId>hibernate-jpa-2.0-api</artifactId> <groupId>org.hibernate.javax.persistence</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.hibernate</groupId>...

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

java,mysql,hibernate

You can use the AssociationOverride annotation to accomplish this: http://www.objectdb.com/api/java/jpa/AssociationOverrides...

distinct & trim in JPA with hibernate 3.2.6

oracle,hibernate,jpa

This exception usually happens when you have some column/expression in order by clause which you don't have in select clause, in combination with distinct. Without knowing the actual JPQL query you are executing, here is an example that should work select distinct trim(addressInfo.city) from AddressInfo addressInfo where <some conditions> order...

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

java,hibernate,criteria,many-to-one

Try adding alias : criteria.createAlias("documentMovement.docMaster", "docMaster") And later call criteria.add(Restrictions.ne("docMaster.status",FMSConstants.CLOSED_STATUS)); ...

unable to pass two lits to the jsp using apachi tiles

hibernate,jsp,spring-mvc,tiles

You're adding the attributes and sending redirect. It will lose all the informations that you set. If you redirect to the page it will show it right. Example: 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 "successPage"; }else{ model.addAttribute("error", "ERROR : invaliduser !,Please Try Again!"); return "loginform"; } If you...

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

java,spring,hibernate,postgresql

You can try setting the default schema for the jdbc user. 1) ALTER USER user_name SET search_path to 'schema' 2) Did you try this property? spring.datasource.schema http://docs.spring.io/spring-boot/docs/current/reference/html/howto-database-initialization.html...

How to pass parameter in HQL query

sql,hibernate,hql

I is very simple to add parameter to an HQL Query query = session.createQuery("select u from UserLog u where u.userLogSerialno = " + "(select max(uu.userLogSerialno) from UserLog uu where uu.userId = :userId)").setParameter("userId", 15); here i have hard coded 15 you can simply use variable instead of it...

to generate a table with list using hbm file

java,hibernate,arraylist

You need to tell Hibernate to create the table if it does not already exist. So add this line directly underneath <hibernate-mapping> in your ClassTime.hbm.xml: <property name="hbm2ddl.auto" value="create"/> ...

Not able to typecast from object to class:

java,spring,hibernate

From your query it looks like you are fetching Host , StorageInfo , ServerStorage and while getting the Object (StorageInfo) info.get(0) you are trying to cast it into only StorageInfo. So try removing Host and Serverstorage from your query or else if you want to fetch records from 3 tables...

NullPointerError on saveOrUpdate Hibernate

java,spring,hibernate

you should probable give some information. As far as I can see, both the pa variable as the productAvailibilityService could be null at this time where the exception is invoked. Have you debugged and checked the pa is set correctly, and the service is also available?...

Defining Transient Pojo (Object) Fields in Hibernate

hibernate

You can't apply annotations to methods or fields randomly. Normally, you should apply your annotations the same way as @Id.. In EntCariHareketler class Transientshould be like @Transient private EntHesaplasma enthesaplasma; ...

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

java,hibernate

Your mapping is a bidirectional association. with your UserBean as Parent and LoginBean as Child. So you have 2 mappings to user_id table @Column(name = "user_id", nullable = false) private Integer userid; And @ManyToOne @ElementCollection(targetClass = fordream.hibernate.bean.UserBean.class) private UserBean user; with userid and user.id trying to map to user_id. Totally...

Hibernate delete child when parent is getting updated in same transaction

hibernate,spring-data

Please share your beans. Given your descriptionI expect you should have: @Entity @Table(name="CUSTOMER") public class Customer implements Serializable { private static final long serialVersionUID = -4505027246487844609L; @Id private String username; @OneToMany(cascade=CascadeType.ALL, orphanRemoval=true, fetch=FetchType.EAGER) @Fetch(FetchMode.SUBSELECT) @JoinColumn(name="ORDER_USERNAME", nullable = false) private List<SalesOrder> salesOrders; } The important part is: @OneToMany(cascade=CascadeType.ALL, orphanRemoval=true,...

DTOs with different granularity

java,spring,hibernate,design-patterns,dto

I would go with as little different queries as possible. I would rather make associations lazy in my mappings, and then let them be initialized on demand with appropriate Hibernate fetch strategies. I think that there is nothing wrong in having multiple different DTO classes per one business model entity,...

DTOs and entities which implements the same interface

java,android,spring,hibernate,jpa

Based on past experience, I do not think it is a good idea to use an interface that is shared between the DTO model and the JPA model. You are in essence tightly coupling your DTO model to your JPA model with this approach. I would rather have them loosely...

Hibernate Domain Object Generation

java,mysql,hibernate,code-generation

The Telosys Tools code generator is probably the solution for you. It uses an existing database to generate any kind of source file for each entity (database table), typically POJO, DTO, DAO, web pages, etc... When the database schema change you just have to regenerate. For more information see the...

Optimistic locking not throwing exception when manually setting version field

hibernate,jpa,spring-data-jpa

Unfortunately, (at least for Hibernate) changing the @Version field manually is not going to make it another "version". i.e. Optimistic concurrency checking is done against the version value retrieved when entity is read, not the version field of entity when it is updated. e.g. This will work Foo foo =...

Hibernate Query cache invalidation

java,hibernate,jpa,caching,concurrency

The query cache is not useful for write-mostly applications, as you probably figured out yourself. There is no write-through query caching option, so you need to question why you are using this feature in the first place. The entity caching is useful when you plan on changing those entities you’re...

Is it possible to add Stored procedure dynamically from hibernate?

java,mysql,sql,hibernate,stored-procedures

So I found out what was wrong in the baove stored procedure: The use of DELIMITER is not required, begin with CREATE PROCEDURE the use of "\n" is also not required, but it will not prompt an error if used. You can't use DROP and CREATE in the same query,...

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

java,xml,spring,hibernate,spring-mvc

your property name is userWordDao in class UserWordServiceImpl , and you are trying to set property userWordDAO (case mismatch) which is not there . So in spring.xml change <bean id="userWordService" class="com.memorize.service.impl.UserWordServiceImpl"> <property name="userWordDAO" ref="userWordDAO"></property> </bean> to <bean id="userWordService" class="com.memorize.service.impl.UserWordServiceImpl"> <property name="userWordDao" ref="userWordDAO"></property> </bean> ...

Envers Pre/PostCollection Listener

java,hibernate,jpa,hibernate-envers

That's when you have persistent collections, e.g. fields of type List<String>, or Set<EmbeddedComponent>.

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

java,spring,hibernate,dozer

@Transactional(readOnly=true) tells Spring that the operation will not be modifying the DB, in such a case it sets the connection to read-only and Hibernate will not update the entity. If you remove the readOnly=true you will see that even using HibernateTemplate.get() the change will be persisted. If you use SessionFactory.getCurrentSession()...

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

hibernate,jpa-2.0

You can create a database agnostic model, with JPA @Entity's, meaning that your model will work using different DB. Usually you code your @Entity, an generate the right DDL using SchemaGenerator tool (or other tool) that will create the proper statements for a specific database (using the specified dialect). Your...

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

java,hibernate,jpa,pagination,spring-data

Only way I can see is to map an entity to the join table and replace the many-to-many Product<>Category with one-to-many relationships pointing to this new entity from both Product and Category. Such a change would actually be in line with Hibernate best practices: https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/best-practices.html Do not use exotic association...

JPA try to delete if fails set inactive

java,hibernate,jpa

A better approach (just idea, details depend on JPA provider): public void deleteB(B b) { Long count = entityManager.createQuery("select count(a) from A a where a.b.id = :b") .setParameter("b", b.getId()) .getSingleResult): if (count == 0L) { // delete B } else { // make B inactive } } Handling your specific...

How to delete multiple rows in Hibernate

java,hibernate

the user you fetch in getUserByID is queried in its own session which is closed and the user returned is detached. You should have one session per Request but you have nested sessions. Try opening a session and a transaction at the beginning of the Request and commit the transaction...