hibernate,jpa-2.0 , JPA2 get column metadata (type, lenth, nullable, etc)


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

Question:

Tag: 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 long it is.


Answer:

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 schema is DB agnostic, but at runtime, the proper dialect must be specified.

Be aware that certain key generation mechanism aren't available to some DB and should be avoided to be truly DB agnostic.

Using the @Column annotation on a field, you can define nullable, length etc. If you use the "datatype" property, its becomes your responsibility to use a cross DB type if you want to remain DB agnostic.

There are also other @Temporal & @Enumarated that can influence generated data types.

-- Alternative

You can also map existing table to entities. There are also tools that will do it. By example : http://help.eclipse.org/juno/index.jsp?topic=%2Forg.eclipse.jpt.doc.user%2Ftasks021.htm

Be aware to you might have to tweak your mapping / model a bit to be truly database agnostic, as the generated @Entity's mapping may reflect some database specific data types that were used to create the model in the first place.

To my knowledge, generally speaking, JPA is DB agnostic by itself, unless you force datatypes or use unsupported key generation mechanism. It is the right framework to create DB agnostic models.

Even if it may be possible, i don't believe JPA is the right tool to inspect DB types are runtime. So if by "retrieve" you mean inspect and adapt at runtime... you might be better of using straight JDBC. If you need to inspect DB at runtime and react accordingly, it is the opposite of DB agnostic code, you treat all possible cases.


Related:


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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