In JPA (Hibernate), when we automatically generate the ID field, it is assumed that the user has no knowledge about this key. So, when obtaining the entity, user would query based on some field other than ID. How do we obtain the entity in that case (since em.find() cannot be used).
I understand we can use a query and filter the results later. But, is there a more direct way (because this is a very common problem as I understand).
It is not a "problem" as you stated it.
Hibernate has the built-in find(), but you have to build your own query in order to get a particular object. I recommend using Hibernate's Criteria :
Criteria criteria = session.createCriteria(YourClass.class);
YourObject yourObject = criteria.add(Restrictions.eq("yourField", yourFieldValue))
.uniqueResult();
This will create a criteria on your current class, adding the restriction that the column "yourField" is equal to the value yourFieldValue. uniqueResult() tells it to bring a unique result. If more objects match, you should retrive a list.
List<YourObject> list = criteria.add(Restrictions.eq("yourField", yourFieldValue)).list();
If you have any further questions, please feel free to ask. Hope this helps.
if you have repository for entity Foo and need to select all entries with exact string value boo (also works for other primitive types or entity types). Put this into your repository interface:
List<Foo> findByBoo(String boo);
if you need to order results:
List<Foo> findByBooOrderById(String boo);
See more at reference.
Basically, you should add a specific unique field. I usually use xxxUri fields.
class User {
#Id
// automatically generated
private Long id;
// globally unique id
#Column(name = "SCN", nullable = false, unique = true)
private String scn;
}
And you business method will do like this.
public User findUserByScn(#NotNull final String scn) {
CriteriaBuilder builder = manager.getCriteriaBuilder();
CriteriaQuery<User> criteria = builder.createQuery(User.class);
Root<User> from = criteria.from(User.class);
criteria.select(from);
criteria.where(builder.equal(from.get(User_.scn), scn));
TypedQuery<User> typed = manager.createQuery(criteria);
try {
return typed.getSingleResult();
} catch (final NoResultException nre) {
return null;
}
}
Best practice is using #NaturalId annotation. It can be used as the business key for some cases it is too complicated, so some fields are using as the identifier in the real world.
For example, I have user class with user id as primary key, and email is also unique field. So we can use email as our natural id
#Entity
#Table(name="user")
public class User {
#Id
#Column(name="id")
private int id;
#NaturalId
#Column(name="email")
private String email;
#Column(name="name")
private String name;
}
To get our record, just simply use 'session.byNaturalId()'
Session session = sessionFactory.getCurrentSession();
User user = session.byNaturalId(User.class)
.using("email","huchenhai#qq.com")
.load()
This solution is from Beginning Hibernate book:
Query<User> query = session.createQuery("from User u where u.scn=:scn", User.class);
query.setParameter("scn", scn);
User user = query.uniqueResult();
I solved a similar problem, where I wanted to find a book by its isbnCode not by your id(primary key).
#Entity
public class Book implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
private String isbnCode;
...
In the repository the method was created like #kamalveer singh mentioned. Note that the method name is findBy+fieldName (in my case: findByisbnCode):
#Repository
public interface BookRepository extends JpaRepository<Book, Integer> {
Book findByisbnCode(String isbnCode);
}
Then, implemented the method in the service:
#Service
public class BookService {
#Autowired
private BookRepository repo;
public Book findByIsbnCode(String isbnCode) {
Book obj = repo.findByisbnCode(isbnCode);
return obj;
}
}
Write a custom method like this:
public Object findByYourField(Class entityClass, String yourFieldValue)
{
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
CriteriaQuery<Object> criteriaQuery = criteriaBuilder.createQuery(entityClass);
Root<Object> root = criteriaQuery.from(entityClass);
criteriaQuery.select(root);
ParameterExpression<String> params = criteriaBuilder.parameter(String.class);
criteriaQuery.where(criteriaBuilder.equal(root.get("yourField"), params));
TypedQuery<Object> query = entityManager.createQuery(criteriaQuery);
query.setParameter(params, yourFieldValue);
List<Object> queryResult = query.getResultList();
Object returnObject = null;
if (CollectionUtils.isNotEmpty(queryResult)) {
returnObject = queryResult.get(0);
}
return returnObject;
}
Edit: Just realized that #Chinmoy was getting at basically the same thing, but I think I may have done a better job ELI5 :)
If you're using a flavor of Spring Data to help persist / fetch things from whatever kind of Repository you've defined, you can probably have your JPA provider do this for you via some clever tricks with method names in your Repository interface class. Allow me to explain.
(As a disclaimer, I just a few moments ago did/still am figuring this out for myself.)
For example, if I am storing Tokens in my database, I might have an entity class that looks like this:
#Data // << Project Lombok convenience annotation
#Entity
public class Token {
#Id
#Column(name = "TOKEN_ID")
private String tokenId;
#Column(name = "TOKEN")
private String token;
#Column(name = "EXPIRATION")
private String expiration;
#Column(name = "SCOPE")
private String scope;
}
And I probably have a CrudRepository<K,V> interface defined like this, to give me simple CRUD operations on that Repository for free.
#Repository
// CrudRepository<{Entity Type}, {Entity Primary Key Type}>
public interface TokenRepository extends CrudRepository<Token, String> { }
And when I'm looking up one of these tokens, my purpose might be checking the expiration or scope, for example. In either of those cases, I probably don't have the tokenId handy, but rather just the value of a token field itself that I want to look up.
To do that, you can add an additional method to your TokenRepository interface in a clever way to tell your JPA provider that the value you're passing in to the method is not the tokenId, but the value of another field within the Entity class, and it should take that into account when it is generating the actual SQL that it will run against your database.
#Repository
// CrudRepository<{Entity Type}, {Entity Primary Key Type}>
public interface TokenRepository extends CrudRepository<Token, String> {
List<Token> findByToken(String token);
}
I read about this on the Spring Data R2DBC docs page, and it seems to be working so far within a SpringBoot 2.x app storing in an embedded H2 database.
No, you don't need to make criteria query it would be boilerplate code you just do simple thing if you working in Spring-boot:
in your repo declare a method name with findBy[exact field name].
Example-
if your model or document consist a string field myField and you want to find by it then your method name will be:
findBymyField(String myField);
All the answers require you to write some sort of SQL/HQL/whatever. Why? You don't have to - just use CriteriaBuilder:
Person.java:
#Entity
class Person {
#Id #GeneratedValue
private int id;
#Column(name = "name")
private String name;
#Column(name = "age")
private int age;
...
}
Dao.java:
public class Dao {
public static Person getPersonByName(String name) {
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
CriteriaBuilder cb = session.getCriteriaBuilder();
CriteriaQuery<Person> cr = cb.createQuery(Person.class);
Root<Person> root = cr.from(Person.class);
cr.select(root).where(cb.equal(root.get("name"), name)); //here you pass a class field, not a table column (in this example they are called the same)
Query query = session.createQuery(cr);
query.setMaxResults(1);
List<Person> resultList = query.getResultList();
Person result = resultList.get(0);
return result;
}
}
example of use:
public static void main(String[] args) {
Person person = Dao.getPersonByName("John");
System.out.println(person.getAge()); //John's age
}
Have a look at:
JPA query language: The Java Persistence Query Language
JPA Criteria API: Using the Criteria API to Create Queries
I've written a library that helps do precisely this. It allows search by object simply by initializing only the fields you want to filter by: https://github.com/kg6zvp/GenericEntityEJB
Refer - Spring docs for query methods
We can add methods in Spring Jpa by passing diff params in methods like:
List<Person> findByEmailAddressAndLastname(EmailAddress emailAddress, String lastname);
// Enabling static ORDER BY for a query
List<Person> findByLastnameOrderByFirstnameAsc(String lastname);
In my Spring Boot app I resolved a similar type of issue like this:
#Autowired
private EntityManager entityManager;
public User findByEmail(String email) {
User user = null;
Query query = entityManager.createQuery("SELECT u FROM User u WHERE u.email=:email");
query.setParameter("email", email);
try {
user = (User) query.getSingleResult();
} catch (Exception e) {
// Handle exception
}
return user;
}
This is very basic query :
Entity : Student
#Entity
#Data
#NoArgsConstructor
public class Student{
#Id
#GeneratedValue(generator = "uuid2", strategy = GenerationType.IDENTITY)
#GenericGenerator(name = "uuid2", strategy = "uuid2")
private String id;
#Column(nullable = false)
#Version
#JsonIgnore
private Integer version;
private String studentId;
private String studentName;
private OffsetDateTime enrollDate;
}
Repository Interface : StudentRepository
#Repository
public interface StudentRepository extends JpaRepository<Student, String> {
List<Student> findByStudentName(String studentName);
List<Student> findByStudentNameOrderByEnrollDateDesc(String studentName);
#Transactional
#Modifying
void deleteByStudentName(String studentName);
}
Note:
findByColumnName : give results by criteria
List findByStudentName(String studentName)
Internally convert into query : select * from Student where name='studentName'
#Transactional
#Modifying
Is useful when you want to remove persisted data from database.
Using CrudRepository and JPA query works for me:
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
public interface TokenCrudRepository extends CrudRepository<Token, Integer> {
/**
* Finds a token by using the user as a search criteria.
* #param user
* #return A token element matching with the given user.
*/
#Query("SELECT t FROM Token t WHERE LOWER(t.user) = LOWER(:user)")
public Token find(#Param("user") String user);
}
and you invoke the find custom method like this:
public void destroyCurrentToken(String user){
AbstractApplicationContext context = getContext();
repository = context.getBean(TokenCrudRepository.class);
Token token = ((TokenCrudRepository) repository).find(user);
int idToken = token.getId();
repository.delete(idToken);
context.close();
}
Related
I'm trying to integrate Hibernate Search to my backend, but I can't make it work as I would like it to.
My intention is to retrieve all the following model.Course tuples only with the token "java":
Currently, I'm only getting the model.Course with id = 26. That means Lucene is working, but I don't know how to create the query needed to perform the operation I want.
This is my CourseService code:
private Session session;
private FullTextSession fts;
public CourseService(){
SessionFactory sf = SessionFactoryManager.getInstance(); // Singleton
this.session = sf.openSession();
this.fts = Search.getFullTextSession(this.session);
}
public List<Course> searchCourses(String token) {
try {
this.fts.createIndexer().startAndWait();
} catch (InterruptedException e) {
e.printStackTrace();
}
Transaction tx = this.fts.beginTransaction();
QueryBuilder queryBuilder = this.fts.getSearchFactory()
.buildQueryBuilder()
.forEntity(Course.class)
.get();
org.apache.lucene.search.Query query = queryBuilder.simpleQueryString()
.onField("description").andField("name")
.matching(token)
.createQuery();
org.hibernate.query.Query hibQuery = fts.createFullTextQuery(query, Course.class);
List result = hibQuery.getResultList();
tx.commit();
return result;
}
This is my model.Course code:
#Entity
#Indexed
#Inheritance(strategy = InheritanceType.JOINED)
public class Course implements Comparable<Course>{
#Id
#DocumentId
#GeneratedValue(strategy= GenerationType.AUTO)
private int id;
#Field (termVector = TermVector.YES)
private String name;
#Field
private String description;
/*...*/
protected Course(String name, String description, ...) {
/*...*/
}
IMPORTANT EDIT: I initially thought it was a problem with the query, but it's actually an indexing problem.
I don't know how to solve this type of problem. I'm hearing suggestions. Details:
I'm using a singleton for SessionFactory (I wasn't before the edit)
I'm using org.hibernate:hibernate-search-orm:5.8.2.Final
I'm using HSQLdb 2.4.0
The rest of hibernate is working perfectly (CRUD operations)
It looks like an analysis issue, e.g. the analyzer chosen not splitting the field in tokens.
What is a bit weird is that the default analyzer (the StandardAnalyzer) split the field in tokens so it should work out of the box.
Have you set a different default analyzer (the KeywordAnalyzer for instance)?
I am unable to to get a list of nested objects using a JpaRepository. I'll try to explain what I want using the following code:
AutoService entity:
#Entity
public class AutoService {
#Id
private long id;
#Column(name = "serviceName", nullable = false)
private String serviceName;
}
Service entity:
#Entity
public class Service {
#Id
private long serviceId;
#Column(name = "serviceName", nullable = false)
private String serviceName;
#Column(name = "category", nullable = false)
private String category;
#ManyToOne
#JoinColumn(name = "autoServiceId", nullable = false)
private AutoService autoService;
}
ServiceRepository interface:
public interface ServiceRepository extends JpaRepository<Service, Long> {
List<Service> findByServiceNameAndCategory(String autoServiceName, String categoryName);
}
Business logic:
#org.springframework.stereotype.Service
public class ServiceServiceImpl implements ServiceService {
#Autowired
private ServiceRepository serviceRepository;
#Override
public List<Service> findByAutoServiceAndCategory(String autoServiceName, String serviceCategory) {
return serviceRepository.findByServiceNameAndCategory(autoServiceName, serviceCategory);
}
}
As I am expecting, the code above is unable to provide the desired list of Services matching the provided category and AutoService names.
Can someone provide advice on how should I use my repository to get list of nester services by: autoServiceName and serviceCategory please?
EDIT:
Right now I am using the custom query.
I am using autoServiceId instead of service name right now.
But for some reason I am getting empty list of objects.
Here is my JPA Repo.
public interface ServiceRepository extends JpaRepository<Service, Long> {
#Query("SELECT s from Service s where s.autoService.id = :autoServiceId and s.category = :categoryName")
List<Service> findByServiceNameAndCategory(#Param("autoServiceId") Long autoServiceId, #Param("categoryName") String categoryName);
}
Any suggestions please ?
I think i know the answer. Problem in my category, sended to the server. I wrote it on Russian language. And encoding broken value of category on server side.
1- Use #Embedded and #Embeddable annotation accordingly on your entity object then your method will fetch nested object.
OR
2- #Query annotation is used for writing custom query please refer this link custom query reference
You may have to write a query like this in your ServiceRepository.
public interface ServiceRepository extends JpaRepository<Service, Long> {
#Query("SELECT s from Service s where s.autoService.serviceName = :autoServiceName and s.category = :categoryName")
Set<Round> getRoundsBySessionQuestionId(#Param("autoServiceName") String autoServiceName, #Param("categoryName") String categoryName);
}
Hope this helps. Happy coding !
Since you have a serviceName attribute in both AutoService and Service entities, ServiceRepository.findByServiceNameAndCategory is equivalent to the following SQL query:
SELECT
*
FROM
Service
WHERE
serviceName = ?
AND category = ?
As seen, this query does not hit the AutoService entity at all, which is why the results are not as expected.
The correct repository method is:
public interface ServiceRepository extends JpaRepository<Service, Long> {
List<Service> findByCategoryAndAutoServiceServiceName(String category, String autoServiceName);
}
This method will search the nested AutoService object by its serviceName, as expected.
A sample project is available on Github to show this in action.
It's possible mapping custom native/named queries to entities? I have something like this
NamedQueries({
NamedQuery(name = "StateBo.findByCountry", query = "SELECT state FROM StateBo state WHERE state.country.id = ?"),
NamedQuery(name = "StateBo.showIdfindByCountry", query = "SELECT state.id FROM StateBo state WHERE state.country.id = ?")
})
#Table(name = "STATE")
#Entity(name = "StateBo")
public class StateBo extends BaseNamedBo {
private static final long serialVersionUID = 3687061742742506831L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "STATE_ID")
private Long id;
#Column(name = "ISO_CODE")
private String isoCode;
#ManyToOne
#JoinColumn(name = "COUNTRY_ID")
private CountryBo country;
// getters and setters ...
}
I have my method to call Native/Named queries like this.
#Override
public List<E> executeQuery(String queryName, List<Object> criteria) {
TypedQuery<E> query = entityManager.createNamedQuery(queryName, entityClass);
Integer argumentPosition = 1;
if ( (criteria != null) && (criteria.size() > 0) ){
for(Object object : criteria) {
query.setParameter(argumentPosition, object);
argumentPosition++;
}
}
return (List<E>) query.getResultList();
}
When I call the StateBo.findByCountry the result is mapped to StateBo, but if I call StateBo.showIdfindByCountry the result is not mapped to StateBo because I'm only selected on the query the state.id instead of the fields on the table.
I don't want to select all the fields of the STATE table, I only want in this case the state.id, but when I customize my native query, the result is not mapped to StateBo instead of this, the result is a Long type.
My question is, Is possible map to an Entity the result of StateBo.showIdfindByCountry? I case that I have more fields like state.isoCode, is possible map to StateBo, the custom query? or only is possible if I return all the fields from the query, like the first query StateBo.findByCountry
It is possible, but as JB Nizet said - "your collegues will suffer from such a design decision".
Anyway, in order to do that you should create custom constructor in your entity class. This constructor should accept Long argument and assign it to id field of your entity class.
Then you should change your query to include NEW keyword followed by full qualified entity class name as below:
SELECT NEW your.package.StateBo(sb.id)
FROM StateBo sb
WHERE state.country.id = ?
Please note that all entities retreived from database in such a way will not be managed by persistence context.
In hibernate, for example I have two object which has relation. The object is like this
First object : Customer
#Entity
#Table(name = "customer", catalog = "test")
public class Customer implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private String name;
private Set<CustomerController> customerControllers = new HashSet<CustomerController>(0);
public Customer() {
}
//getter & setter
}
Second Object : CustomerController
#Entity
#Table(name = "customer_controller", catalog = "test")
public class CustomerController implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private Customer customer;
//constructor, getter & setter
}
I want to select the customer_controller of certain customer. I get it by two manner. First manner :
#Override
public List<CustomerController> customerController(int customerId){
Customer customer = (Customer) sessionFactory.getCurrentSession().get(Customer.class, customerId);
return customer.getCustomerControllers()
}
Second manner :
return (List<CustomerController>)sessionFactory.getCurrentSession().createQuery("SELECT O FROM CustomerController O WHERE O.customerId=:CONDITION")
.setParameter("CONDITION", customerId)
.list();
Which manner is the most efficient one? Why?
Thank you.
To ensure it is easier to "turn on" show SQL parameter and monitor it.
I suppose in first hibernate able to generate two SQL query with entity mapping.
In second case should be generated only one select query.
In case when we use FetchType.EAGER think Hibernate will map Customer and CustomerController entity. Hope Hibernate fetch only CustomerController using HQL. To ensure you should monitor Hibernate behavior.
I want to ask, it is possible that I create query projections and criterion for more than one level deep?
I have 2 model classes:
#Entity
#Table(name = "person")
public class Person implements Serializable {
#Id
#GeneratedValue
private int personID;
private double valueDouble;
private int valueInt;
private String name;
#OneToOne(cascade = {CascadeType.ALL}, orphanRemoval = true)
#JoinColumn(name="wifeId")
private Wife wife;
/*
* Setter Getter
*/
}
#Entity
#Table(name = "wife")
public class Wife implements Serializable {
#Id
#GeneratedValue
#Column(name="wifeId")
private int id;
#Column(name="name")
private String name;
#Column(name="age")
private int age;
/*
* Setter Getter
*/
}
My Criteria API :
ProjectionList projections = Projections.projectionList();
projections.add(Projections.property("this.personID"), "personID");
projections.add(Projections.property("this.wife"), "wife");
projections.add(Projections.property("this.wife.name"), "wife.name");
Criteria criteria = null;
criteria = getHandlerSession().createCriteria(Person.class);
criteria.createCriteria("wife", "wife", JoinType.LEFT.ordinal());
criterion = Restrictions.eq("wife.age", 19);
criteria.add(criterion);
criteria.setProjection(projections);
criteria.setResultTransformer(Transformers.aliasToBean(Person.class));
return criteria.list();
and I hope, I can query Person, with specified criteria for wife property, and specified return resultSet.
so i used Projections for getting specified return resultSet
I want personID, name(Person), name(Wife) will returned. how API i must Use, i more prefer use Hibernate Criteria API.
This time, I used code above for getting my expected result, but it will throw Exception with error message :
Exception in thread "main" org.hibernate.QueryException: could not resolve property: wife.name of: maladzan.model.Person,
and whether my Restrictions.eq("wife.age", 19); is correct for getting person which has wife with 19 as her age value ?
Thanks
AFAIK it is not possible to project more than one level deep with aliastobean transformer. Your options are
create a flattened Data Transfer Object (DTO)
fill the resulting Person in memory yourself
implement your own resulttransformer (similar to option 2)
option 1 looks like this:
Criteria criteria = getHandlerSession().createCriteria(Person.class)
.createAlias("wife", "wife", JoinType.LEFT.ordinal())
.add(Restrictions.eq("wife.age", 19));
.setProjection(Projections.projectionList()
.add(Projections.property("personID"), "personID")
.add(Projections.property("name"), "personName")
.add(Projections.property("wife.name"), "wifeName"));
.setResultTransformer(Transformers.aliasToBean(PersonWifeDto.class));
return criteria.list();
I wrote the ResultTransformer, that does this exactly. It's name is AliasToBeanNestedResultTransformer, check it out on github.
Thanks Sami Andoni. I was able to use your AliasToBeanNestedResultTransformer with a minor modification to suit my situation. What I found was that the nested transformer did not support the scenario where the field is in a super class so I enhanced it to look for fields up to 10 levels deep in the class inheritance hierarchy of the class you're projecting into:
public Object transformTuple(Object[] tuple, String[] aliases) {
...
if (alias.contains(".")) {
nestedAliases.add(alias);
String[] sp = alias.split("\\.");
String fieldName = sp[0];
String aliasName = sp[1];
Class<?> subclass = getDeclaredFieldForClassOrSuperClasses(resultClass, fieldName, 1);
...
}
Where getDeclaredFieldForClassOrSuperClasses() is defined as follows:
private Class<?> getDeclaredFieldForClassOrSuperClasses(Class<?> resultClass, String fieldName, int level) throws NoSuchFieldException{
Class<?> result = null;
try {
result = resultClass.getDeclaredField(fieldName).getType();
} catch (NoSuchFieldException e) {
if (level <= 10){
return getDeclaredFieldForClassOrSuperClasses(
resultClass.getSuperclass(), fieldName, level++);
} else {
throw e;
}
}
return result;
}
My Hibernate projection for this nested property looked like this:
Projections.projectionList().add( Property.forName("metadata.copyright").as("productMetadata.copyright"));
and the class I am projecting into looks like this:
public class ProductMetadata extends AbstractMetadata {
...
}
public abstract class AbstractMetadata {
...
protected String copyright;
...
}
Instead of creating Data Transfer Object (DTO)
In projectionlist make below changes and it will work for you.
ProjectionList projections = Projections.projectionList();
projections.add(Projections.property("person.personID"), "personID");
projections.add(Projections.property("person.wife"), "wife");
projections.add(Projections.property("wife.name"));
Criteria criteria = null;
criteria = getHandlerSession().createCriteria(Person.class,"person").createAlias("person.wife", "wife");
criterion = Restrictions.eq("wife.age", 19);
criteria.add(criterion);
criteria.setProjection(projections);
criteria.setResultTransformer(Transformers.aliasToBean(Person.class));
return criteria.list();