JPA - Retrieving data from database table wrt Foreign key - - java

I am trying to retrieve data from a table which has a foreign key, "reg_no". And the foreign key is not unique, it can be duplicated.
Now I want to retrieve the data from this table using this foreign key. I will provide a "reg_no" and the Java Persistence API will retrieve a list of the result set from the table wrt to "reg_no" provided.
Please enlighten me how can I solve this problem?

You can do something like this, using JPQL:
String queryString = "SELECT t FROM YourTable t " +
"WHERE reg_no = :regNo";
Query query = getEntityManager().createQuery(queryString);
query.setParameter("regNo", regNoValue);
return query.getResultList();

EntityManager entityManager = entityManagerFactory.createEntityManager();
List results = em.createQuery("SELECT c FROM Vehicle v WHERE reg_no = :reg_no").setParameter("reg_no", new String("0000")).getResultList;

Related

JPQL Extract pk of an relation entity without a second query

I have these entities (is an example because i cant share real name entities):
#Entity
public class User { #Id private BigDecimal id; private String name, private Color favouriteColor }
#Entity
public class Color { #Id private Long colorId; private String colorName;}
In the table I have this data:
USER
ID|NAME|FavColor
1 |John| 1
2 |Sarah| 2
3 |Mike| 1
COLOR
1|Red
2|Blue
Now I want make a query that recover all my user data without select Color entity, only its ids.
#Query("new myDto(u.iduser,u.username,u.favcolor) from user u where favcolor in :listcolors")
This makes me an query of the two tables, I want a unique query because i dont need color entities, only the ids.
--
Other option that I am testing is making a implementation of a nativequery like this:
final List<MyDTO> result = new ArrayList<>();
Query q = entityManager.createNativeQuery("SELECT " +
" USER_ID, " +
" USER_NAME, " +
" FAV_COLOR " + +
"FROM USER " +
"WHERE FAV_COLOR IN (?)");
q.setParameter(1, colors.toString().replace("[","").replace("]",""));
Long TRUE = new Long(1L);
final List<Object[]> resultList = q.getResultList();
for (Object[] objects : resultList) {
MyDTOdto = new MyDTO();
dto.userId(((((BigDecimal) objects[0]) != null) ? ((BigDecimal) objects[0]).longValue() : null));
dto.userName(((((String) objects[0]) != null) ? ((String) objects[0]).longValue() : null));
dto.favColor(((((BigDecimal) objects[0]) != null) ? ((BigDecimal) objects[0]).longValue() : null));
result.add(dto);
}
return result;
In this case, I am getting error code (ORA-1722 - Number Not valid). I don't know what I can test now. Some ideas? Thanks
I am guessing you have issues with the SQL generated and your use of the inner join: when you call "u.favcolor" in the select clause, you are telling JPA to perform an inner join from User to Color based on the favcolor relationship. As favcolor is a Color reference, you are going to get the full color row, where as your native query implies you just want the foreign key value. If all you want is the fk/ID value from Color, the query should be:
"SELECT new myDto(u.iduser, u.username, color.id) FROM user u join u.favcolor color WHERE color.id in :listcolors"
This still might perform an inner join from user to color, but it should be in a single statement.
If you want to ensure you avoid the join:
Use EclipseLink's COLUMN JPQL extension to access the foreign key column directly. Something like:
"SELECT new myDto(u.iduser, u.username, COLUMN('FAV_COLOR', u) FROM user u WHERE COLUMN('FAV_COLOR', u) in :listcolors"
Use EclipseLink native query key functionality to access the "FAV_COLOR" foreign key column in the USER table directly for your JPQL queries. This requires a descriptor customizer to access, but allows you to use the foreign key value in JPQL queries directly without having to map it, and without the COLUMN mechanism tying your JPQL queries to a particular database table detail. This would allow a query of the form:
"SELECT new myDto(u.iduser, u.username, u.favColorVal FROM user u join u.favcolor color WHERE u.favColorVal in :listcolors"
Just map the FAV_COLOR as a basic mapping, in addition to the existing favColor reference mapping (or replacing it if you want):
#Basic
#Column(name="FAV_COLOR", updatable=false, insertable=false)
BigDecimal favColorId
This then allows you to use query "SELECT new myDto(u.iduser, u.username, u.favColorId FROM user u join u.favColorId color WHERE u.favColorId in :listcolors" to the same effect, but you can also just return the User instance (marking favColor as lazy and not serializable) as it will have the same data anyway.

JPA - Select All Rows from Dynamic Table Name

Hi guys I am new to jpa, named queries, etc.. and I need something like this:
select t from :tableName t
Later in code I want something like this:
em.createQuery(...);
setParameter("tableName", "Person")
Result would be:
select * from person
How to write such a generic jpa query statement allowing to select all rows from :tableName which may be defined at runtime? thanks in advance
Try this I think this works well
EntityManagerFactory emfactory=Persistence.createEntityManagerFactory("Eclipselink_JPA" );
EntityManager entitymanager = emfactory.createEntityManager();
Query query = entitymanager.
createQuery("Select p from Person p");
List<String> list = query.getResultList();
setParameter("foo", foo) is used to set the value for column of the table not to set the table name. I do not think it will work, as you want to set the table name dynamically.
You can try this:
public returnType foo(String tableName){
String jpql = "SELECT t FROM " + tableName+ " t";
Query query = em.createQuery(jpql);
//rest of the code
}

QueryDSL: Query by composite primary key

I have an entity Parte with a composite primary key. These are the columns:
codabast
codejerc
codparte
I have annotated my entity with #IdClass(PartePK.class). Now, to perform a query by primary key, I do this:
JPAQuery query = new JPAQuery(entityManager);
query.from(qParte).where(qParte.codabast.eq(myCodAbast)
.and(qParte.codejerc.eq(myCodEjerc)
.and(qParte.codparte.eq(myCodParte))));
Parte p = query.singleResult(qParte);
Is it needed to do it field by field? Or does exist a way to query by primary key?
I would like something like this:
PartePK primaryKey = new PartePK(3, 4, 6);
query.from(qParte).byId(primaryKey);
Thanks in advance.

How to call oracle function using Hibernate criteria?

I am new to Hibernate. I am building a Login Portal. We have used DB Function to encrypt User Password. It seems that using hibernate for complex queries/functions/procedures on existing databases is difficult.
Is it possible to write below queries using Hibernate criteria?
SQL Query 1 :
SELECT first_name
FROM user.emp_group
WHERE username = 'XXX'
AND user.decrypt(password, 2) = 'YYYY';
SQL Query 2 :
SELECT a.DESC
,b.total
FROM user.STATUS a
,(
SELECT STATUS
,count(*) total
FROM user.emp
GROUP BY STATUS
) b
WHERE a.TYPE = b.STATUS (+)
User is the schema name and decrypt is function name.
I also faced problem for getting data from views which was resolved by this Stackoverflow post. How hibernate retrieve data from existing database view?
Thanks for that.
You can use native SQL with hibernate.
The way is something like this (for example):
String sql = "SELECT first_name, salary FROM EMPLOYEE";
SQLQuery query = session.createSQLQuery(sql);
List data = query.list();
for(Object object : data)
{
Map row = (Map)object;
System.out.print("First Name: " + row.get("first_name"));
System.out.println(", Salary: " + row.get("salary"));
}

Hibernate, search by primary key returns all from table

I have this issue with Hibernate that when i try to retrieve unique result using criteria hibernate returns all the content from the table.
Session session = HibernateUtil.beginTransaction();
Customer c = new Customer();
c.setCustId(custId);
Example ex = Example.create(c);
Criteria criteria = HibernateUtil.getSession().createCriteria(Customer.class);
criteria.add(ex);
Customer customer = (Customer)criteria.uniqueResult();
HibernateUtil.commitTransaction();
HibernateUtil.closeSession();
However querying the table with:
Customer customer = (Customer)session
.createSQLQuery("select * from customer_ where custid = :id")
.addEntity(Customer.class)
.setInteger("id", custId)
.uniqueResult();
returns correct entry.
custId is the table's primary key. And the Customer class contains 2 #OneToMany mappings.
Do I need to add something to the criteria example above??
The documentation says:
Version properties, identifiers and associations are ignored.
(emphasis mine)
Why not simply using Session.get() if you have the identifier?

Categories