I have a entity as below
public class Employee implements Serializable {
#Id
#Column(name = "EMPSEQ")
#GeneratedValue(strategy = GenerationType.AUTO)
private Long empSeq;
#Column(name = "EMPID")
private String empId;
#Column(name = "WINDOWSLOGINID")
private String logInId;
// assume respective getter and setter methods
}
I want to query all row where logInId does not start with "5"
I tried below code:
query = session.createQuery("select * from Employee e where e.logInId not like 5%");
the above code didn't work. what is the right way to use NOT LIKE in HQL
In your query there's an error:
query = session.createQuery("select * from Employee e where e.logInId not like 5%");
become:
query = session.createQuery("select * from Employee e where e.logInId not like '5%'");
e.logInId is string, so you must quote your condition 5%.
You can also use Hibernate Criteria for the same.
JPA EntityManger has unwrap() method which will return session.
Session session = getEntityManager().unwrap(Session.class);
Criteria criteria = session.createCriteria(Pojo.class);
criteria.add(Restrictions.not(Restrictions.like("loginId","5%")));
List<Pojo> list=criteria.list();
if(null!=list && list.size()> 0){
return list.get(0);
}
return null;
Related
in my java web application i need to inquire a list of deposits from a view named VwDepositsInfo by customerNumber.
when i execute my query:
select * from VW_DEPOSIT_INFO v where v.CUSTOMER_NUMBER=:customerNo
in database console my resultList size is 2 and have something like this:
1-{depositTypeDesc="shortTerm"} {depositTypeCode="850"}
2-{depositTypeDesc="longTerm"} {depositTypeCode="2"}
but when i test my code that includes a namedQuery:
#NamedQuery(
name = "inquireAccountByCustomerNumber",
query = "select c from VWDepositInfo c where c.customerNumber=:customerNo"
)
i get a resultList with size 2 but both the same, sth like this:
1-{depositTypeDesc="shortTerm"} {depositTypeCode="850"}
2-{depositTypeDesc="shortTerm"} {depositTypeCode="850"}
when i make it nativeQuery with defining the result class:
Query query = entityManager.createNativeQuery("select * from VW_DEPOSIT_INFO v where v.CUSTOMER_NUMBER=:customerNo", VWDepositInfo.class);
again i get the wrong results.
finally i tried nativeQuery without defining the result class:
Query query = entityManager.createNativeQuery("select * from VW_DEPOSIT_INFO v where v.CUSTOMER_NUMBER=:customerNo");
and result was as i expected to be.
and this is my VwDepositsInfo.class:
#Entity
#Table(name = "VW_DEPOSIT_INFO")
#Audited(withModifiedFlag = false)
#NamedQueries(
{#NamedQuery(
name = "inquireAccountByCustomerNumber",
query = "select c from VWDepositInfo c where c.customerNumber=:customerNo"
)
}
)
public class VWDepositInfo implements Serializable {
#Id
#Column(name = "CUSTOMER_NUMBER")
private Long customerNumber;
#Column(name = "BRANCH_CODE")
private Long branchCode;
#Column(name = "DEPOSIT_TYPE_CODE")
private Long depositTypeCode;
#Column(name = "DEPOSIT_SERIAL")
private Long depositSerial;
#Column(name = "DEPOSIT_TYPE_DESC")
private String depositTypeDesc;
#Column(name = "CURRENCY_TYPE_DESC")
private String currencyTypeDesc;
#Column(name = "DEPOSIT_OPEN_DATE")
private Date depositOpenDate;
Does anyone know why this is happening???
VW = view?
You probably need to specify the master key
use #id for unique field :)
you probably need more than one field with #id for a unique row.
for example both of DEPOSIT_TYPE_CODE and customerNumber
I am trying to fetch specific fields from my entities. I need the result in my entity structure.
Following are my entities:
Country
public class CountryModel {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "CmtID")
private int id;
#Column(name = "CmtName")
private String name;
#JoinColumn(name="CmtStateID")
#OneToMany(targetEntity=StateModel.class,fetch=FetchType.EAGER)
private List<StateModel> state;
}
State
public class StateModel {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "SmtID")
private int id;
#Column(name = "SmtName")
private String name;
}
Following is the HQL query am executing:
Query query = session.createQuery("select c.name, s.name from CountryModel c join c.state s where c.id=2");
CountryModel stateModel = (CountryModel) query.uniqueResult();
But am getting the following error:
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.muziris.entity.CountryModel
Thanks for helping.
Expected result:
Country :
name : india
state :
name : kerala
name : goa
name : Pak
state :
name : karachi
Since your classes are mapped you can try:
Query query = session.createQuery("from CountryModel c where c.id=2");
CountryModel countryModel = (CountryModel) query.uniqueResult();
Let's make use of the mapping and HQL.
From there you can use a DTO to have only the data that you need
public CountryDTO transform(CountryModel cm){
String countryName = cm.getName();
List<String> stateNames = cm.getState().stream.map(StateModel::getName)
.collect(Collectors.toList());
return new CountryDTO(countryName, stateNames);
}
CountryDTO is the result that you need.
Hibernate returns List<Object[]> when you use the projections.
List<Object[]> is a list of specified projection columns.
Some links
https://stackoverflow.com/a/36883968/3405171
How to transform a flat result set using Hibernate
I'm using Hibernate and JPA. I have entity class CompanyRate.
CompanyRate.java
#Entity
public class CompanyRate {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int idRate;
#Column(nullable = false)
private int atmosphere;
#Column(nullable = true)
private int salary;
#Column(nullable = false)
private int opportunityToDevelop;
#Column(nullable = false)
private int socialPackage;
#ManyToOne(targetEntity = User.class)
private User user;
#ManyToOne(targetEntity = Company.class)
Company company;
}
I want to display AVG values of atmosphere, salary, opportunityToDevelop, socialPackage where company.idComapny = ? on JSP.
Ofc I can use getResultList() on executed query and diplay it on JSP using . But I wanna assign each result for single variable. What is the best way to do it?
What you're asking is equivalent to the following SQL:
SELECT c.id,
AVG(t.atmosphere),
AVG(t.salary),
AVG(t.opportunityToDevelop),
AVG(t.socialPackage)
FROM table t, company c
WHERE t.companyid = c.id
AND c.id IN (:companyIds)
GROUP BY c.id;
Translating the above into HQL/JPQL or leveraging Hibernate or JPA criteria APIs should be a trivial exercise.
Just be sure to call setParameter("companyIds", listOfCompanyIds) on the constructed Query and then call getResultList() or list() depending on the API you use.
Database data:
pkmn_id | pkmn_name
1 | Charmander
These are my entity:
Pokemon.Class
#Entity
#Table(name = "pkmn")
#Inheritance(strategy = InheritanceType.JOINED)
#NamedQuery(name = "#GET_POKEMON_BY_ID", query = "SELECT pkmn FROM Pokemon as pkmn FireType as ft WHERE pkmn.pkmnID = pkmn.fireAttributes[0]")
public abstract class Pokemon {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE)
#Column(name = "pkmn_id")
private int pkmnID;
#Column(name = "pkmn_name")
private String pkmnName;
public long[] fireAttributes = { 1, 2, 3, 4, 5 };
FireType.class
#Entity
#Table(name = "pkmn_firetype")
#DynamicUpdate(value = true)
#SelectBeforeUpdate(value = true)
public class FireType extends Pokemon {
#Column(name = "fire_immunity")
private int fireImmunity;
#Column(name = "fire_attack")
private int fireAttack;
PokemonServlet.class
SessionFactory sessionFactory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
Query query2 = session.getNamedQuery("#GET_POKEMON_BY_ID");
FireType pk2 = (FireType) query2.uniqueResult();
System.out.println(pk2.getFireAttack());
session.getTransaction().commit();
session.close();
I have an error in my NamedQuery, the problem is on how I used the array index in the WHERE clause. I'm confused with the right way of including an indexed collection in the WHERE clause.
What is the correct way of implementing this query, wherein the pkmn_id must match the value in the index of an array to retrieve the correct object?
This is my reference
JBoss Hibernate Documentation
You forgot to put comma only. Your query should be as below and use in when you are comparing id with more than one.
SELECT pkmn FROM Pokemon as pkmn , FireType as ft WHERE pkmn.pkmnID in pkmn.fireAttributes[0]
I have a JPA object:
#Entity
#Table(name="WF_GROUP")
public class Group {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String groupName;
private long parentId;
/* ... */
}
I have a GroupDAO with this method:
public List<Group> getAllGroups() {
List<Group> groups = new ArrayList<Group>();
String query = "select * from WF_GROUP";
Query q = getEntityManager().createNativeQuery(query);
groups.addAll( q.getResultList() );
return groups;
}
The problem is the q.getResultList() returns a result list of type Object than contains an object array for each property.
Why doesn't q.getResultList() return a list of Group objects?
Thanks!
Rob
Because you don't specify which class the native query should return. Have a look at the other createNativeQuery methods, taking additional arguments.
Note that the point of using JPA is to use objects rather than database tables. JPQL is there for that. You should use the following code:
String query = "select group from Group group"; // this is JPQL
TypedQuery<Group> q = getEntityManager().createQuery(query, Group.class);
groups.addAll(q.getResultList());