Populate DTO using query with JOIN - java

I have this main Product table:
#Table(name = "product")
public class Product implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", unique = true, updatable = false, nullable = false)
private int id;
#Column(name = "user_id", length = 20)
private Integer userId;
#Column(name = "title", length = 75)
private String title;
#Column(name = "meta_title", length = 100)
private String metaTitle;
#Column(name = "status", length = 100)
private String status;
}
Additional table for storing categories that should be returned as List:
#Table(name = "product_category")
public class ProductCategory implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", unique = true, updatable = false, nullable = false)
private int id;
#Column(name = "product_id", length = 4)
private Integer productId;
#Column(name = "category_id", length = 20)
private Integer categoryId;
}
Additional table for storing Payment Methods that should be returned as List:
#Table(name = "product_payment_methods")
public class ProductPaymentMethods implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", unique = true, updatable = false, nullable = false)
private int id;
#Column(name = "product_id", length = 20)
private Integer productId;
#Column(name = "payment_methods", length = 20000)
private String paymentMethods;
}
I want to return a result like this:
id | title | categoryId | paymentMethods |
1 | test | 34, 43 | 345, 7, 5 |
5 | test2 | 64,5, 3 | 654, 3, 5 |
I tried this:
SELECT *
FROM Product
INNER JOIN product_category ON Product.id = product_category.productId
INNER JOIN product_payment_methods ON Product.id = product_payment_methods.productId
WHERE userId = 1
What is the proper way to populate this DTO?
public class ProductFullDTO {
private int id;
private Integer userId;
private List<Integer> categories;
private List<String> paymentMethods;
}

If, as indicated in your comments, you need query your information with HQL a good way to proceed can be the following.
First, modify your Product entity an include relationships for both ProductCategory and ProductPaymentMethods, something like:
#Table(name = "product")
public class Product implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", unique = true, updatable = false, nullable = false)
private int id;
#Column(name = "user_id", length = 20)
private Integer userId;
#Column(name = "title", length = 75)
private String title;
#Column(name = "meta_title", length = 100)
private String metaTitle;
#Column(name = "status", length = 100)
private String status;
#OneToMany(mappedBy = "product", cascade = CascadeType.ALL, orphanRemoval = true)
private List<ProductCategory> categories;
#OneToMany(mappedBy = "product", cascade = CascadeType.ALL, orphanRemoval = true)
private List< ProductPaymentMethods> paymentMethods;
// Setters and getters, omitted for brevity
}
Modify both ProductCategory and ProductPaymentMethods to accommodate the entities relationship:
#Table(name = "product_category")
public class ProductCategory implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", unique = true, updatable = false, nullable = false)
private int id;
// Please, feel free to change the insertable and updatable attributes to
// fit your needs
#Column(name = "product_id", length = 4, insertable=false, updatable=false)
private Integer productId;
#ManyToOne(fetch= FetchType.LAZY)
#JoinColumn(name="product_id")
private Product product;
#Column(name = "category_id", length = 20)
private Integer categoryId;
// Setters and getters, omitted for brevity
}
#Table(name = "product_payment_methods")
public class ProductPaymentMethods implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", unique = true, updatable = false, nullable = false)
private int id;
// Please, feel free to change the insertable and updatable attributes to
// fit your needs. By the way, why here the length is 20 and not 4?
#Column(name = "product_id", length = 20, insertable=false, updatable=false)
private Integer productId;
#ManyToOne(fetch= FetchType.LAZY)
#JoinColumn(name="product_id")
private Product product;
#Column(name = "payment_methods", length = 20000)
private String paymentMethods;
}
With this setup, as you can see in the Hibernate documentation - it is for an old Hibernate version, but it is correct today, you can use fetch joins to obtain the required information:
A "fetch" join allows associations or collections of values to be initialized along with their parent objects using a single select. This is particularly useful in the case of a collection.
For your example, consider the following HQL (assume outer join semantics, modify it as appropriate):
select product
from Product as product
left join fetch product.categories
left join fetch product.paymentMethods
where product.userId = 1
This will provide you the list of products for userId 1, with all the associated references to categories and payment methods initialized.
The conversion between the entity and the DTO should be straightforward:
Session session = ...
List<Product> products = session.createQuery(
"select product " +
"from Product as product " +
" left join fetch product.categories " +
" left join fetch product.paymentMethods " +
"where product.userId = :userId", Product.class)
.setParameter( "userId", 1)
.getResultList();
List<ProductFullDTO> productFullDTOs = null;
if (products != null) {
productFullDTOs = products.stream()
.map((product -> {
ProductFullDTO productFullDTO = new ProductFullDTO();
productFullDTO.setId(product.getId());
productFullDTO.setUserId(product.getUserId());
List<ProductCategory> categories = product.getCategories();
if (categories != null) {
List<Integer> categoriesIds = categories.stream()
.map(ProductCategory::getCategoryId)
.collect(Collectors.toList())
;
productFullDTO.setCategories(categoriesIds);
}
List<ProductPaymentMethods> paymentMethods = product.getPaymentMethods();
if (paymentMethods != null) {
List<String> paymentMethodsIds = paymentMethods.stream()
.map(ProductPaymentMethods::getPaymentMethods)
.collect(Collectors.toList())
;
productFullDTO.setPaymentMethods(paymentMethodsIds);
}
return productFullDTO;
}))
.collect(Collectors.toList())
;
}
System.out.println(productFullDTOs == null ? "No products found." : productFullDTOs.size() + " products found.");

You should use TypeHandler to finish this job. I just give paymentMethods as example.
#Results({
#Result(column = "product.id", property = "id"),
#Result(column = "user_id", property = "userId"),
#Result(column = "category_id", property = "categories"),
#Result(column = "payment_methods", property = "paymentMethods" ,typeHandler= StrListTypeHandler.class),
})
#Select("SELECT * FROM Product INNER JOIN product_category ON Product.id = product_category.productId "
+ " INNER JOIN product_payment_methods ON Product.id = product_payment_methods.productId "
+ " WHERE userId = 1")
List<ProductFullDTO> getProduct();
// the below is TypeHandler implementation
#Component
public class StrListTypeHandler implements TypeHandler<List<String>> {
#Override
public void setParameter(PreparedStatement preparedStatement, int i, List<String> strings, JdbcType jdbcType) throws SQLException {
StringBuffer sb = new StringBuffer();
for (String s : strings) {
sb.append(s).append(",");
}
preparedStatement.setString(i, sb.toString().substring(0, sb.toString().length() - 1));
}
#Override
public List<String> getResult(ResultSet resultSet, String s) throws SQLException {
String[] arr = resultSet.getString(s).split(",");
return Arrays.asList(arr);
}
#Override
public List<String> getResult(ResultSet resultSet, int i) throws SQLException {
String[] arr = resultSet.getString(i).split(",");
return Arrays.asList(arr);
}
#Override
public List<String> getResult(CallableStatement callableStatement, int i) throws SQLException {
String[] arr = callableStatement.getString(i).split(",");
return Arrays.asList(arr);
}
}

Related

Duplicate parent and child data in jpql (JPA)

I have a Production class and ProductionDetail entity class where Id of Production table is a foreignKey as production_id in ProductionDetail entity class so my both entity class with mapping has given bellow
Production Entity Class:
#Entity
#Table(name = "tbl_production")
#XmlRootElement
public class TblProduction implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "ID")
private String id;
#Column(name = "PRODUCTION_DATE")
#Temporal(TemporalType.DATE)
private Date productionDate;
#Column(name = "START_DATETIME")
#Temporal(TemporalType.TIMESTAMP)
private Date startDatetime;
#Column(name = "END_DATETIME")
#Temporal(TemporalType.TIMESTAMP)
private Date endDatetime;
#Size(max = 45)
#Column(name = "MACHINE_UUID")
private String machineUuid;
**Relation with Production Details Table**
#OneToMany(mappedBy = "production")
#XmlElement(name = "productionDetails")
private List<TblProductionDetail> productionDetailList;
#PrimaryKeyJoinColumn(name = "MACHINE_UUID", referencedColumnName = "UUID")
#ManyToOne(fetch = FetchType.LAZY)
private MstMachine mstMachine;
#XmlTransient
public MstMachine getMstMachine() {
return this.mstMachine;
}
}
Production Details Entity Class:
#Entity
#Table(name = "tbl_production_detail")
#XmlRootElement
public class TblProductionDetail implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "ID")
private String id;
#Size(max = 45)
#Column(name = "COMPONENT_ID")
private String componentId;
#Size(max = 45)
#Column(name = "PRODUCTION_ID")
private String productionId;
**Relation with Production Class**
#ManyToOne
#JoinColumn(name = "PRODUCTION_ID", referencedColumnName = "ID", insertable = false,
updatable = false)
private TblProduction production;
#Transient
public String componentCode;
#Transient
public String componentName;
#PrimaryKeyJoinColumn(name = "COMPONENT_ID", referencedColumnName = "ID")
#ManyToOne(fetch = FetchType.LAZY)
private MstComponent mstComponent;
#XmlTransient
public MstComponent getMstComponent() {
return this.mstComponent;
}
public void setMstComponent(MstComponent mstComponent) {
this.mstComponent = mstComponent;
}
}
ParentList Class:
public class TblProductionList {
private List<TblProduction> productionList;
public TblProductionList() {
productionList = new ArrayList<>();
}
public List<TblProduction> getTblProductions() {
return productionList;
}
public void setTblProductions(List<TblProduction> tblProductionList) {
this.productionList = tblProductionList;
}
}
BusinessLogic(DAO Class):
public TblProductionList getJson() {
TblProductionList response = new TblProductionList();
StringBuilder retrieveQuery = new StringBuilder();
retrieveQuery.append(" SELECT prod FROM TblProduction prod ");
retrieveQuery.append(" JOIN FETCH prod.productionDetailList ");
retrieveQuery.append(" WHERE prod.endDatetime IS NULL ");
retrieveQuery.append(" AND prod.machineUuid IS NOT NULL ");
retrieveQuery.append(" AND NOT EXISTS (SELECT tpt FROM
TblProductionThset tpt WHERE prod.id = tpt.productionId) ");
retrieveQuery.append(" AND EXISTS (SELECT mmfd FROM
MstMachineFileDef mmfd WHERE prod.machineUuid = mmfd.machineUuid
AND mmfd.hasThreshold = 1) ");
retrieveQuery.append(" ORDER BY prod.id ");
Query query =
entityManager.createQuery(retrieveQuery.toString());
List thresholdList = query.getResultList();
response.setTblProductions(thresholdList);
return response;
}
According to the database I am getting expected master child data like below
After designing this entity class I am expecting that I will get 3 master records where each record has 2 detail records. But I am getting 6 duplicate master records with 12 child records. Can anyone suggest to me please where is my code became wrong and why this situation raised? please check the JSON data that I am getting from API.
change your array list to hash set then records are not duplicate.

Trying to get a result set from a table with a joined table using Criteria API in Java

I have three mapped entities, an item, a user and a company.
There is a table that defines the user and their relationship to the company (for permissions)
I'm trying to find all of these items that are either owned by the user, or owned by companies that they have permission to view / edit.
I can get the query to work easily in native SQL, I just cannot get it to work with criteria builder. It will have dynamic filters and ordering, so using native queries gets messy with string concatenation.
#Entity
public class Item implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "item_id")
private Integer itemId;
#Basic(optional = false)
#NotNull
#Lob
#Size(min = 1, max = 65535)
#Column(name = "title")
private String title;
#JoinColumn(name = "company_id", referencedColumnName = "company_id")
#ManyToOne
private Company companyId;
#JoinColumn(name = "user_id", referencedColumnName = "user_id")
#ManyToOne(optional = false)
private Users userId;
... getters and setters...
}
#Entity
public class CompanyUsers implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "company_user_id")
private Integer companyUserId;
#Basic(optional = false)
#NotNull
#Column(name = "edit_company")
private boolean editCompany;
#JoinColumn(name = "company_id", referencedColumnName = "company_id")
#ManyToOne(optional = false)
private Company companyId;
#JoinColumn(name = "user_id", referencedColumnName = "user_id")
#ManyToOne(optional = false)
private Users userId;
... getters and setters...
}
#Entity
public class Company implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "company_id")
private Integer companyId;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 256)
#Column(name = "company_name")
private String companyName;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "companyId")
private Collection<CompanyUsers> companyUsersCollection;
...getters and setters...
}
#Entity
public class Users implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "user_id")
private Integer userId;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 128)
#Column(name = "email_address")
private String emailAddress;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "user")
private Collection<Item> itemCollection;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "userId", orphanRemoval = true)
private Collection<CompanyUsers> companyUsersCollection;
...getters and setters...
/*
Then the attempt and getting this right with Criteria Builder.
*/
public List<Item> findAllItem(Users selectedUser, int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, Object> filters) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Item> cq = cb.createQuery(Item.class);
Root<Item> item = cq.from(Item.class);
CriteriaQuery<Item> select = cq.select(item);
Subquery<CompanyUsers> subquery = cq.subquery(CompanyUsers.class);
Root<CompanyUsers> companyUsers = subquery.from(CompanyUsers.class);
subquery.select(companyUsers)
.distinct(true)
.where(cb.equal(companyUsers.get("userId"), selectedUser));
if (sortField == null) {
sortField = "itemId";
}
if (sortOrder.equals(SortOrder.ASCENDING)) {
cq.orderBy(cb.asc(item.get(sortField)));
} else if (sortOrder.equals(SortOrder.DESCENDING)) {
cq.orderBy(cb.desc(item.get(sortField)));
}
List<Predicate> predicateList = new ArrayList<>();
predicateList.add(cb.equal(item.get("userId"), selectedUser));
predicateList.add(cb.in(item.get("companyId")).value(subquery));
filters.entrySet().forEach((filter) -> {
if (filter.getKey().equals("itemStatus") || filter.getKey().equals("itemId")) {
predicateList.add(cb.equal(item.get(filter.getKey()), filter.getValue().toString()));
} else {
predicateList.add(cb.like(item.get(filter.getKey()), "%" + filter.getValue().toString() + "%"));
}
});
Predicate[] predicateArray = predicateList.stream().toArray(Predicate[]::new);
cq.where(predicateArray);
TypedQuery<Item> typedQuery = em.createQuery(select);
if (first >= 0) {
typedQuery.setFirstResult(first);
}
if (pageSize >= 0) {
typedQuery.setMaxResults(pageSize);
}
return typedQuery.getResultList();
}
I've not included all the column names here, but there are more.
This produces the following sql:
SELECT t0.title AS a2, t0.item_id AS a1 FROM item t0, company_users t1 WHERE ((t0.user_id = ?) AND (t1.user_id = ?)) ORDER BY t0.item_id ASC LIMIT ?, ?
Which is close to either of the following:
select title, item_id, cu.company_id from item s left join company_users as cu on cu.company_id = s.company_id where s.user_id = 2 or cu.user_id = 2;
or
select title,item_id from item s where s.user_id = 2 or s.company_id in (select company_id from company_users where user_id = 2) ;
The above two native queries are what I'm trying to achieve. I cannot get the criteria builder to work using either a Join or Subquery.
public List<Item> findAllItem(Users selectedUser, int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, Object> filters) {
ArrayList<String> filterItems = new ArrayList<>();
Map<String, Object> parameterMap = new HashMap<String, Object>();
filters.entrySet().forEach((filter) -> {
switch (filter.getKey()) {
case "userStatus":
filterItems.add(" AND s.statusType = :statusType");
parameterMap.put("statusType", (String) filter.getValue());
break;
case "title":
filterItems.add(" AND s.title like :title");
parameterMap.put("title", "%" + (String) filter.getValue() + "%");
break;
default:
break;
}
});
}
String sortDirection;
if (sortOrder.equals(SortOrder.ASCENDING)) {
sortDirection = "ASC";
} else {
sortDirection = "DESC";
}
String sortString;
if (sortField == null) {
sortString = "s.itemId";
} else {
switch (sortField) {
case "title":
sortString = "s.title";
break;
case "statusType":
sortString = "s.statusType";
break;
case "startDate":
sortString = "s.startDate";
break;
case "endDate":
sortString = "s.endDate";
break;
default:
sortString = "s.itemId";
break;
}
}
Query query = em.createQuery("SELECT s from Item s WHERE (s.userId = :userId or s.companyId in "
+ "(SELECT cu.companyId from CompanyUsers cu WHERE cu.userId = :userId))"
+ String.join(" ", filterItems)
+ " ORDER BY " + sortString + " " + sortDirection,
Item.class);
query.setParameter("userId", selectedUser);
for (String key : parameterMap.keySet()) {
query.setParameter(key, parameterMap.get(key));
}
if (first >= 0) {
query.setFirstResult(first);
}
if (pageSize >= 0) {
query.setMaxResults(pageSize);
}
List<Item> result = query.getResultList();
return result;
}

The constructor Category(String, String) is not visible - create constructor for some field using lombok?

I did googled a lot, still dont find any solution hence posting a question here..
I am developing Many-To-Many relationship example using lombok. I just want to create argument constructor for only two fields out of four. How we can do that ?
#Data
#Entity
#Table(name = "stock")
public class Stock implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "STOCK_ID", unique = true, nullable = false)
private Integer stockId;
#Column(name = "STOCK_CODE", unique = true, nullable = false, length = 10)
private String stockCode;
#Column(name = "STOCK_NAME", unique = true, nullable = false, length = 20)
private String stockName;
#ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinTable(name = "stock_category", joinColumns = {
#JoinColumn(name = "STOCK_ID", nullable = false, updatable = false)},
inverseJoinColumns = {#JoinColumn(name = "CATEGORY_ID", nullable = false, updatable = false)})
private Set<Category> categories = new HashSet<Category>(0);
}
Category
#Data
#RequiredArgsConstructor(staticName = "of")
#Entity
#Table(name = "category")
public class Category {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "CATEGORY_ID", unique = true, nullable = false)
private Integer categoryId;
#Column(name = "NAME", nullable = false, length = 10)
#NonNull
private String name;
#Column(name = "[DESC]", nullable = false)
#NonNull
private String desc;
#ManyToMany(fetch = FetchType.LAZY, mappedBy = "categories")
private Set<Stock> stocks = new HashSet<Stock>(0);
}
App.java
Why cant I set the limitted field constructor
public class App {
public static void main(String[] args) {
System.out.println("Hello World!");
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Stock stock = new Stock();
stock.setStockCode("7052");
stock.setStockName("PADINI");
Category category1 = new Category("CONSUMER", "CONSUMER COMPANY");
Category category2 = new Category("INVESTMENT", "INVESTMENT COMPANY");
Set<Category> categories = new HashSet<Category>();
categories.add(category1);
categories.add(category2);
stock.setCategories(categories);
session.save(stock);
session.getTransaction().commit();
System.out.println("Done");
}
}
The reason is that
If staticName set, the generated constructor will be private, and an additional
static 'constructor' is generated with the same argument list that
wraps the real constructor.
Please, don't forget about #NoArgsConstructor because Hibernate needs it.

Caused by: java.sql.SQLException: Column 'id' not found

I want to get some fields and then set it to my Test.entity. My SQL query:
query = "SELECT t.id as tId, t.test_name, t.duration, q.id as qId, " +
"q.question as question, q.is_multichoice as is_multichoice, " +
"q.is_open as is_open, a.id as aId, a.answer_text as answer_text FROM result r " +
"JOIN test t ON r.test_id = t.id " +
"JOIN user u ON r.user_id = u.id " +
"JOIN question q ON t.id = q.test_id JOIN answer a ON q.id = a.question_id " +
"WHERE t.id = :testId AND u.id = :userId AND r.permission = :permissionId " +
"AND q.archived = false AND a.archived = false", resultClass = com.bionic.entities.Test.class)
Test Entity:
public class Test {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Column(name = "duration", nullable = false)
private int duration;
#Column(name = "test_name", nullable = false, unique = true)
private String testName;
#Column(name = "archived", nullable = false)
private boolean archived;
#OneToMany(mappedBy = "test", fetch = FetchType.EAGER)
private Set<Question> questions;
#ManyToMany(mappedBy = "tests")
private Set<User> users;
Question Entity:
public class Question {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Column(name = "is_multichoice", nullable = false)
private boolean isMultichoice;
#Column(name = "is_open", nullable = false)
private boolean isOpen;
#Column(name = "picture")
private String picture;
#Column(name = "question")
private String question;
#ManyToOne
#JoinColumn(name = "test_id", nullable = false)
private Test test;
#Column(name = "archived", nullable = false)
private boolean isArchived;
#OneToMany(mappedBy = "question", fetch = FetchType.EAGER)
private Set<Answer> answers;
Answer Entity:
public class Answer {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Column(name = "answer_text", nullable = false)
private String answerText;
#Column(name = "mark", nullable = false)
private int mark;
#ManyToOne
#JoinColumn(name = "question_id")
private Question question;
#Column(name = "picture")
private String picture;
#Column(name = "archived", nullable = false)
private boolean isArchived;
However, after executing this query i am getting exeption :
Caused by: java.sql.SQLException: Column 'id' not found.
DAO.class:
public Test getCurrentTest(long id, long testId, long permissionId) {
Query query = em.createNamedQuery("getCurrentTestById");
query.setParameter("userId", id);
query.setParameter("testId", testId);
query.setParameter("permissionId", permissionId);
return (Test) query.getSingleResult();
}
What am i doing wrong?
Your query doesn't return a field named id. It has fields named aId, qId, and tId.
You need to use the correct column names in your entities. For example, in your Test entity, you declared a column named id. Except your query doesn't return a column named id, it returns a column named tId. See below for an example of what needs to be changed.
public class Test {
#tId
#Column(name = "tId")
#GeneratedValue(strategy = GenerationType.AUTO)
private long tId;
....

How to fetch data from multiple table query by hibernate?

I have a user management application that allocate each user a team and one or many access to different application. Now for the reporting page I am trying to fetch data from two table (UserInfo & UserAppAccess) by Hibernate but I can't.
Here are the tables :
Table 1 (UserInfo):
#Entity
#Table(name = "user_info", uniqueConstraints = { #UniqueConstraint(columnNames = "username"), #UniqueConstraint(columnNames = "email") })
public class UserInfo implements java.io.Serializable {
public enum UserStatus {
active, inactive
}
public enum UserType {
user, creator
}
private static final long serialVersionUID = 2650114334774359089L;
#Id
#Column(name = "id", unique = true, nullable = false, length = 100)
private String id;
#Column(name = "username", unique = true, nullable = false, length = 50)
private String username;
#Column(name = "password", nullable = false, length = 80)
private String password;
#Column(name = "status", nullable = false, length = 10)
#Enumerated(EnumType.STRING)
private UserStatus status;
#Column(name = "type", nullable = false, length = 10)
#Enumerated(EnumType.STRING)
private UserType type;
#Column(name = "phone", nullable = true, length = 30)
private String phone;
#Column(name = "email", nullable = true, length = 50)
private String email;
#Column(name = "first_name", nullable = true, length = 50)
private String firstName;
#Column(name = "last_name", nullable = true, length = 50)
private String lastName;
#Column(name = "login", nullable = true, length = 100)
private long login;
#Column(name = "alert", nullable= true, length=500)
private String alert;
#OneToOne
#JoinColumn(name = "team_id")
private Team team;
}
Table 2 (Team):
#Entity
#Table(name = "team", uniqueConstraints = { #UniqueConstraint(columnNames = "team_name"), #UniqueConstraint(columnNames = "team_code") })
public class Team implements java.io.Serializable {
private static final long serialVersionUID = 7933770163144650730L;
#Id
#Column(name = "id", unique = true, nullable = false, length = 80)
private String id;
#Column(name = "team_name", unique = true, nullable = false, length = 100)
private String name;
#Column(name = "team_code", unique = true, nullable = false, length = 10)
private String code;
}
Table 3 (Access):
#Entity
#Table(name = "access_def")
public class Access implements java.io.Serializable {
private static final long serialVersionUID = 7933770163144650730L;
#Id
#Column(name = "id", unique = true, nullable = false, length = 80)
private String id;
#Column(name = "access_name", unique = true, nullable = false, length = 100)
private String name;
#Column(name = "access_code", unique = true, nullable = false, length = 10)
private String code;
}
Table 4 (Application):
#Entity
#Table(name = "application", uniqueConstraints = { #UniqueConstraint(columnNames = "name") })
public class Application implements java.io.Serializable {
private static final long serialVersionUID = 5803631085624275364L;
#Id
#Column(name = "name", nullable = false, length = 100)
private String name;
}
Table 5 (UserAppAccess):
#Entity
#Table(name = "user_app_access")
#Embeddable
public class UserAppAccess implements java.io.Serializable {
private static final long serialVersionUID = 7933770163144650730L;
#Id
#Column(name = "id", unique = true, nullable = false, length = 80)
private String id;
#OneToOne
#JoinColumn(name = "user_id")
private UserInfo userInfo;
#Column(name = "app_name", nullable = false, length = 100)
private String appName;
#OneToOne
#JoinColumn(name = "access_id")
private Access access;
}
I have a report page that allow Admin to select multiple options (for example: list all active users in Team test and application APP1).
here is my code to fetch the data but it is not working :
public List<?> getReport(String teamId,String appName,UserStatus active,UserStatus inactive) {
Session session = sessionFactory.getCurrentSession();
String hql = "SELECT u.firstName,u.username,u.status,u.lastName,u.phone,u.team From UserInfo u,AppAccess a WHERE u.status =? OR u.status =? AND u.team.id = ? AND a.appName = :appName ";
Query query = session.createQuery(hql);
query.setParameter(0, active);
query.setParameter(1, inactive);
query.setParameter(2, teamId);
query.setParameter("appName", appName);
System.out.println(query.list());
return query.list();
}
For instance when I pass
Active Users: Active
inactive User:null
team:test
application :app1
teamId :28f66133-26c3-442b-a071-4d19d64ec0aeappName :app1active :activeinactive:null
I am getting this back from my return query.list();
[[Ljava.lang.Object;#2961116f, [Ljava.lang.Object;#23bfa3a2, [Ljava.lang.Object;#7a8ff303, [Ljava.lang.Object;#9b88d2, [Ljava.lang.Object;#6333934d, [Ljava.lang.Object;#4f0bd71c, [Ljava.lang.Object;#125797cf, [Ljava.lang.Object;#34afa071, [Ljava.lang.Object;#764e75bc, [Ljava.lang.Object;#1913c652, [Ljava.lang.Object;#61413e5a, [Ljava.lang.Object;#264b898, [Ljava.lang.Object;#22930462, [Ljava.lang.Object;#6204cfa9, [Ljava.lang.Object;#29dd9285, [Ljava.lang.Object;#11be6f3c, [Ljava.lang.Object;#6d78d53d, [Ljava.lang.Object;#17f7cff1, [Ljava.lang.Object;#e74e382, [Ljava.lang.Object;#1c047338, [Ljava.lang.Object;#68286fe6, [Ljava.lang.Object;#36ca9a76, [Ljava.lang.Object;#2f62d514, [Ljava.lang.Object;#1932c5a, [Ljava.lang.Object;#6544c984, [Ljava.lang.Object;#70a2d0d, [Ljava.lang.Object;#2d13b417, [Ljava.lang.Object;#6894691f, [Ljava.lang.Object;#6781a7dc, [Ljava.lang.Object;#7133919a]
I'd suggest using native SQL and JDBC for reporting (see
How should I use Hibernate Mapping while dealing with huge data table)
For performance reasons it is desirable to create view model objects from result set right in the DAO. It may looks like mixing levels of abstraction (view layer with persistence layer), but it's ok when you need to fetch a big amounts of data and don't want to make unnecessary object transformations from persistence models to view models.
If you're want to stuck with hibernate, you may define a syntetic entity and map if on a view, containing only necessary columns from multiple:
#Entity
#Table("V_USER_REPORT")
public class UserAppData {
// columns from table "user"
#Id
#Column(name = "id", unique = true, nullable = false, length = 100)
private String id;
#Column(name = "username", unique = true, nullable = false, length = 50)
private String username;
// columns from table "user"
#Column(name = "app_name", nullable = false, length = 100)
private String appName;
// columns from table "team"
#Column(name = "team_id", unique = true, nullable = false, length = 80)
private String team_id;
#Column(name = "team_name", unique = true, nullable = false, length = 100)
private String name;
#Column(name = "team_code", unique = true, nullable = false, length = 10)
private String code;
// and so on...
}
Then you fetch such entity by parameters as you do it with normal entity.
By adding LEFT JOIN FETCH or FETCH ALL PROPERTIES. This will force JOINS insteed of lazy initialization
String hql = "SELECT u.firstName,u.username,u.status,u.lastName,u.phone,u.team From UserInfo u,AppAccess a FETCH ALL PROPERTIES WHERE u.status =? OR u.status =? AND u.team.id = ? AND a.appName = :appName ";
More information can be found in HQL Documentation
Firstly: I hope each of your entity classes have a toString() method (can be auto-generated with eclipse) so you can print them. Printing object reference isn't enough to infer whether/not you're getting what you want.
Secondly, the syntax of HQL joins is normally like this:
String queryString = "select distinct f from Foo f inner join foo.bars as b" +
" where f.creationDate >= ? and f.creationDate < ? and b.bar = ?";
(taken from How do you create a Distinct query in HQL)

Categories

Resources