How to iterate List<Tuple> in java - java

I am trying to write JUnit test case for controller class. Below Test case is running properly without any failure. But In that Test case I am checking expected result using Json path. I want to check expected String result with actual String result using AssertEquals() method. For that I want to know
How to iterate List<Tuple> result? I want to iterate this queryResult :
List<Tuple> queryResult = new ArrayList<>();
AccountController class
#GetMapping("/findAccountData")
public ResponseEntity<List<Tuple>> populateGridViews(#RequestParam(value="sClientAcctId",required=false) String sClientAcctId,
#RequestParam(value="sAcctDesc",required=false) String sAcctDesc,
#RequestParam(value="sInvestigatorName",required=false)String sInvestigatorName,
#RequestParam(value="sClientDeptId",required=false) String sClientDeptId) throws Exception {
return ResponseEntity.ok(accService.populateGridViews(sClientAcctId, sAcctDesc,sInvestigatorName,sClientDeptId));
}
Junit Test Case:
#Test
#Transactional
public void populateGridViewsTest() throws Exception {
String sClientAcctId = "5400343";
String sAcctDesc = " ASTRALIS LTD";
String sInvestigatorName = "Krueger, James G.";
String sClientDeptId = "112610";
QAccount account = QAccount.account;
JPAQuery<Tuple> query = new JPAQuery<Tuple>(em);
List<Tuple> result = query.from(account).fetch();
Mockito.when(accountService.populateGridViews(sClientAcctId, sAcctDesc, sInvestigatorName, sClientDeptId))
.thenReturn(result);
mockMvc.perform(get("/spacestudy/$ InstituteIdentifier/admin/account/findAccountData")
.param("sClientAcctId", "5400343")
.param("sAcctDesc", " ASTRALIS LTD")
.param("sInvestigatorName", "Krueger, James G.")
.param("sClientDeptId", "112610")
.accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk())
.andExpect(jsonPath("$[0].sAcctDesc", is(" ASTRALIS LTD")))
.andExpect(jsonPath("$[0].sClientAcctId", is("5400343")))
.andExpect(jsonPath("$[0].sLocation", is("A")))
.andExpect(jsonPath("$[0].investigator.sInvestigatorName", is("Krueger, James G.")))
.andDo(print());
}
}
Account.java
#Entity
#Table(name = "account")
#JsonInclude(JsonInclude.Include.NON_NULL)
public class Account implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "account_seq_generator")
#SequenceGenerator(name = "account_seq_generator", sequenceName = "account_seq")
#Column(name = "naccount_id")
public Integer nAccountId;
#Column(name = "namount")
public String nAmount;
#Column(name = "sacct_desc")
public String sAcctDesc;
#Column(name = "naccount_cpc_mapping_id")
public Integer nAccountCPCMappingId;
#Column(name = "nindirect_cost_rate")
public Integer nIndiretCostRate;
#Column(name = "nagency_id")
public Integer nAgencyId;
#Column(name = "ndept_id")
public Integer nDeptId;
#Column(name = "sgrant_num")
public String sGrantNum;
#Column(name = "dstart_date")
public Timestamp dStartDate;
#Column(name = "dend_date")
public Timestamp dEndDate;
#Column(name = "slocation")
public String sLocation;
#Column(name = "sclient_acct_id")
public String sClientAcctId;
#Column(name = "ninvestigator_id")
public Integer nInvestigatorId;
#Column(name = "ninst_id")
public Integer nInstId;
#Column(name = "ntemp_account_id")
public Integer nTempAccountId;
#ManyToOne(optional = true, cascade = { CascadeType.MERGE })
#JoinColumn(name = "ndept_id", insertable = false, updatable = false)
public Department department;
#ManyToOne(optional = true, cascade = { CascadeType.ALL })
#JoinColumn(name = "ninvestigator_id", insertable = false, updatable = false)
public Investigator investigator;
#ManyToOne(optional = true, cascade = { CascadeType.ALL })
#JoinColumn(name = "naccount_cpc_mapping_id", insertable = false, updatable = false)
public AccountCPCMapping accountCPC;

to iterate list use for example for each:
for (Tuple tuple : queryResult){
'put code and assertion here'
}

Related

hibernate session save method not working?

I 'm new in spring and hibernate. i have a sample project that not work properly. when i try to save new order from user, i get no error or exceprion, but record not inserted into database.
here my code
strong textStoreController.java
#Autowired
OrderService orderService;
#SuppressWarnings("unchecked")
#RequestMapping(value = "/store/addorder", method = RequestMethod.GET)
public ModelAndView addOrder(HttpSession session) {
ModelAndView model = new ModelAndView();
// create list of products that we have to add in orders
List<CartItem> items = (List<CartItem>) session.getAttribute("cart");
Set<CartItem> itemsSet = new HashSet<CartItem>();
// new order generated and setter methods invoke
Orders order = new Orders(itemsSet);
Date d = new Date();
Date delivery = StoreUtils.deliveryDate(d, 3);
order.setOrderDate(d);
order.setDeliveryDate(delivery);
order.setItems(itemsSet);
for (CartItem cartItem : items) {
itemsSet.add(cartItem);
}
String addOrders = orderService.addOrders(order);
System.err.println("new order add status " + addOrders + "-------------");
// change product quantity after adding new order
if (!addOrders.toLowerCase().contains("error")) {
for (int i = 0; i < items.size(); i++) {
Integer qSale = items.get(i).getQuantity() * (-1);
productService.rechargeProduct(items.get(i).getProduct(), qSale);
}
model.setViewName("successorder");
model.addObject("order", order);
model.addObject("message", addOrders);
session.setAttribute("cart", null);
} else {
session.setAttribute("error", addOrders);
model.setViewName("redirect:/addtocartlist");
}
return model;
}
Orders.java
#Entity
#Table(name = "orders")
public class Orders implements Serializable {
private static final long serialVersionUID = -3672662224925418969L;
#Id
#Column(name = "orderid", nullable = false)
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#DateTimeFormat(pattern = "yyyy-mm-dd")
#Column(name = "orderDate", nullable = false)
private Date orderDate;
#DateTimeFormat(pattern = "yyyy-mm-dd")
#Column(name = "delivery", nullable = false)
private Date deliveryDate;
#Column(name = "success", nullable = true, columnDefinition = "tinyint(1) default 0")
private boolean success;
#Column(name = "cancel", nullable = true, columnDefinition = "tinyint(1) default 0")
private boolean canceled;
#Column(name = "cause", nullable = true)
private String cancelCause;
#ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JoinTable(name = "ORDERS_ITEMS", joinColumns = { #JoinColumn(name = "orderid") }, inverseJoinColumns = {
#JoinColumn(name = "item_id") })
private Set<CartItem> items = new HashSet<CartItem>(0);
//setters and getters
}
CartItem.java
#Entity
#Table(name = "items")
public class CartItem implements Serializable {
private static final long serialVersionUID = 7968604053015663078L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "item_id", nullable = false)
private Long id;
#Column(name = "quantity", nullable = false, columnDefinition = "int(11) default 1")
private Integer quantity;
#Column(name = "totalprice", nullable = false)
private BigDecimal totalprice;
#ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JoinColumn(name = "prd_id", nullable = false)
private Product product;
//setters and getters
}
Product.java
#Entity
#Table(name = "products")
public class Product implements Serializable {
private static final long serialVersionUID = -7738539408628995177L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "prd_id")
private Long id;
#Column(name = "full_name", nullable = false)
private String fullName;
#Column(name = "seller_name")
private String seller;
#Column(name = "company_name", nullable = false)
private String companyName;
#Column(name = "created_date")
#DateTimeFormat(pattern = "yyyy-mm-dd")
private Date createdDate;
#Column(name = "expiry_date")
#DateTimeFormat(pattern = "yyyy-mm-dd")
private Date expiryDate;
#Column(name = "insert_date")
#DateTimeFormat(pattern = "yyyy-mm-dd")
private Date insertDate;
#Column(name = "likes", nullable = true)
private Integer likeCount;
#Column(name = "quantity", nullable = true)
private Integer quantity;
#Column(name = "price", nullable = false)
private BigDecimal price;
#Column(name = "category", nullable = false)
private String category;
#Column(name = "description", nullable = true)
private String description;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "product")
private Set<CartItem> items;
//setters and getters
}
and finally here is my doa implementation code
OrdersDaoImpl.java
#Repository("ordersDao")
public class OrdersDaoImpl implements OrdersDao {
#Autowired
SessionFactory sessionFactory;
protected Session session() {
try {
return sessionFactory.getCurrentSession();
} catch (HibernateException e) {
return sessionFactory.openSession();
}
}
public String addOrders(Orders orders) {
String result = "";
try {
session().save(orders);
result = "success";
} catch (Exception e) {
if (e.getMessage().toLowerCase().contains("duplicate"))
result = "error this order already was exist";
else
result = "error " + e.getMessage();
System.err.println(result);
} finally {
session().clear();
}
return result;
}
}
when i try to add new order i get no exception. why my service not work?
i have another controller in my project, that manage users. in that controller and dao implementation add and remove user working properly.
i think i have logic error in my code for one to many and many to many. please help me to overcome this fail.

How to persist entity with joining?

I am confused about how to save entry in db with column's join. I have #Entity bellow
#XmlRootElement
#XmlAccessorType(value = XmlAccessType.FIELD)
#Entity
#Table(name = "psc_users")
#NamedQuery(name = "User.findAll", query = "SELECT u FROM User u")
public class User implements Serializable {
private static final long serialVersionUID = 8885916014620036457L;
#Id
private static final String SEQUENCE_NAME = "psc_users_user_id_seq";
#Id
#GeneratedValue(generator = "UseExistingOrGenerateIdGenerator",
strategy = GenerationType.SEQUENCE)
#GenericGenerator(name = "UseExistingOrGenerateIdGenerator",
strategy = "com.psc.util.UseExistingOrGenerateIdGenerator",
parameters = {
#org.hibernate.annotations.Parameter(name = "sequence", value = SEQUENCE_NAME)
}
)
#Column(name = "USER_ID")
private Long userId;
#Column(name = "DEF", length = 30)
private String def;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "DEL_DATE")
private Date delDate;
#Column(name = "DISPLAY_DEF", length = 60)
private String displayDef;
#Column(name = "EMAIL", length = 60)
private String email;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "NAVI_DATE")
private Date naviDate;
#Column(name = "NAVI_USER")
private String naviUser;
#Column(name = "PHONE", length = 30)
private String phone;
#Column(name = "PWD", length = 40)
private String pwd;
//bi-directional many-to-one association to Branch
#ManyToOne(cascade = CascadeType.MERGE)
#JoinColumn(name = "BRNC_BRNC_ID", nullable = false)
private Branch pscBranch;
public Long getBrncBrncId() {
return brncBrncId;
}
public void setBrncBrncId(Long brncBrncId) {
this.brncBrncId = brncBrncId;
}
#Column(name = "BRNC_BRNC_ID", insertable = false, updatable = false)
private Long brncBrncId;
//bi-directional many-to-one association to User
#ManyToOne(cascade = CascadeType.MERGE)
#JoinColumn(name = "CURATOR_USER_ID")
private User pscUser;
public Long getCuratorUserId() {
return curatorUserId;
}
public void setCuratorUserId(Long curatorUserId) {
this.curatorUserId = curatorUserId;
}
#Column(name = "CURATOR_USER_ID", insertable = false, updatable = false)
private Long curatorUserId;
public User() {
}
public Long getUserId() {
return this.userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getDef() {
return this.def;
}
public void setDef(String def) {
this.def = def;
}
public Date getDelDate() {
return this.delDate;
}
public void setDelDate(Date delDate) {
this.delDate = delDate;
}
public String getDisplayDef() {
return this.displayDef;
}
public void setDisplayDef(String displayDef) {
this.displayDef = displayDef;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getNaviDate() {
return this.naviDate;
}
public void setNaviDate(Date naviDate) {
this.naviDate = naviDate;
}
public String getNaviUser() {
return this.naviUser;
}
public void setNaviUser(String naviUser) {
this.naviUser = naviUser;
}
public String getPhone() {
return this.phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getPwd() {
return this.pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public Branch getPscBranch() {
return this.pscBranch;
}
public void setPscBranch(Branch pscBranch) {
this.pscBranch = pscBranch;
}
public User getPscUser() {
return this.pscUser;
}
public void setPscUser(User pscUser) {
this.pscUser = pscUser;
}
}
if I save User instance without field pscUser (here null) but there is valid CuratorUserId with correct value I end up in a situation with empty CuratorUserId in db. If you look at code then you will see these bound fields.
#ManyToOne(cascade = CascadeType.MERGE)
#JoinColumn(name = "CURATOR_USER_ID")
private User pscUser;
#Column(name = "CURATOR_USER_ID", insertable = false, updatable = false)
private Long curatorUserId;
code to save user
repositoryUser.save(user);
this i see in debugger
this i see in database after saving my user.
sorry for my stupid question but I come across on a different behavior, there is code in my project which behaves in another manner. I don't want to search actual another user(curator) for saving my user, because of overhead on query
The #Column annotation on the curetorUserId field has properties
insertable=false and updatable=false, which means that its value is ignored during inserts and updates.
You can either change these properties to true (but it can break your application in some other places) or just fill in pscUser field using EntityManager.getReference, which just creates a proxy and doesn't actualy produce a query to the database.
Your mapping should look like the below:
#XmlRootElement
#XmlAccessorType(value = XmlAccessType.FIELD)
#Entity
#Table(name = "psc_users")
#NamedQuery(name = "User.findAll", query = "SELECT u FROM User u")
public class User implements Serializable {
private static final long serialVersionUID = 8885916014620036457L;
#Id
private static final String SEQUENCE_NAME = "psc_users_user_id_seq";
#Id
#GeneratedValue(generator = "UseExistingOrGenerateIdGenerator",
strategy = GenerationType.SEQUENCE)
#GenericGenerator(name = "UseExistingOrGenerateIdGenerator",
strategy = "com.psc.util.UseExistingOrGenerateIdGenerator",
parameters = {
#org.hibernate.annotations.Parameter(name = "sequence", value = SEQUENCE_NAME)
}
)
#Column(name = "USER_ID")
private Long userId;
#Column(name = "DEF", length = 30)
private String def;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "DEL_DATE")
private Date delDate;
#Column(name = "DISPLAY_DEF", length = 60)
private String displayDef;
#Column(name = "EMAIL", length = 60)
private String email;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "NAVI_DATE")
private Date naviDate;
#Column(name = "NAVI_USER")
private String naviUser;
#Column(name = "PHONE", length = 30)
private String phone;
#Column(name = "PWD", length = 40)
private String pwd;
//bi-directional many-to-one association to Branch
#ManyToOne(cascade = CascadeType.MERGE)
#JoinColumn(name = "BRNC_BRNC_ID", nullable = false)
private Branch pscBranch;
//bi-directional many-to-one association to User
#ManyToOne(cascade = CascadeType.MERGE)
#JoinColumn(name = "CURATOR_USER_ID")
private User pscUser;
public User() {
}
}
You need to think in terms of objects. The FK will only be set in the database if you set the pscUser reference to an instance of a User. If this is an existing User then you need to set a reference to the existing persistent entity.
Real answer is that I have two points for saving and updating my entity. Please see this Hibernate: Where do insertable = false, updatable = false belong in composite primary key constellations involving foreign keys?

Persisting 2 table with the same generated id

I try to persist one parent entity which is joined with another child entity, but the problem is that the id is not generated for this child when persisting so I have this error : [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] ORA-01400: cannot insert NULL into ("L2S$OWNER"."SABRI"."TRANSITION_MATRIX_ID")
there is the child Entity :
#Data
#Entity
#IdClass(MyLibrarySabriEntityPK.class)
#Table(name = "SABRI", schema = "L2S$OWNER", catalog = "")
public class MyLibrarySabriEntity extends ActionForm {
#Access(AccessType.FIELD)
#Id
#ManyToOne
#JoinColumn(name = "TRANSITION_MATRIX_ID", referencedColumnName = "ID_TRANSITION_MATRIX")
private MyLibraryTestEntity sabriEntity;
#Id
private String RATING_ID_ROW;
#Id
private String RATING_ID_COL;
#Basic
#Column(name = "TRANSITION_PROBABILITY", nullable = true, insertable = true, updatable = true, precision = 20)
private Double TRANSITION_PROBABILITY;}
the PK class :
#Data
public class MyLibrarySabriEntityPK implements Serializable {
private String TRANSITION_MATRIX_ID;
private String RATING_ID_ROW;
private String RATING_ID_COL;
public MyLibrarySabriEntityPK(String TRANSITION_MATRIX_ID,String RATING_ID_COL,String RATING_ID_ROW ){
this.TRANSITION_MATRIX_ID=TRANSITION_MATRIX_ID;
this.RATING_ID_COL = RATING_ID_COL;
this.RATING_ID_ROW= RATING_ID_ROW;
}
}
there is the parent Entity:
#Data
#Entity
#Table(name = "TEST", schema = "L2S$OWNER", catalog = "")
public class MyLibraryTestEntity extends ActionForm {
#Access(AccessType.FIELD)
#OneToMany(mappedBy = "sabriEntity", cascade = CascadeType.PERSIST)
private final List<MyLibrarySabriEntity> entities = new ArrayList<MyLibrarySabriEntity>(25);
public void addEntitysabri(MyLibrarySabriEntity entity) {
getEntities().add(entity);
entity.setSabriEntity(this);
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO, generator = "IdGenerated")
#GenericGenerator(name = "IdGenerated", strategy = "dao.Identifier")
#Column(name = "ID_TRANSITION_MATRIX", nullable = false, insertable = false, updatable = false, length = 10)
private String ID_TRANSITION_MATRIX;
#Basic
#Column(name = "REFERENCE", nullable = true, insertable = true, updatable = true, precision = 0)
private Integer reference;}
And here I try to persist the parent table which is supposed to persist also the child table but the Id is not generated !
MyLibrarySabriEntity Entity = null;
MyLibraryTestEntity test = getMyLibraryTestEntity(matrixStartDate, matrixName); // here I get the values of my entity test (parent)
try {
transaction.begin();
for (int row = 0; row < 20; row++) {
for (int col = 0; col < 20; col++) {
double val = cells.get(row + FIRST_ROW, col + FIRST_COL).getDoubleValue();
Entity = getMyLibrarySabriEntity(col, row, val); // this get the values of the Entity parameters (child)
Entity.setSabriEntity(test);
test.addEntitysabri(Entity);
em.persist(test);
}
}
} catch (Exception e) {
if (transaction.isActive())
transaction.rollback();
LOGGER.warn(e.getMessage(), e);
} finally {
if (transaction.isActive())
transaction.commit();
em.close();
}
Assuming you are using JPA 2.0+
Remove this mapping completely:
#Id
#Column(name = "TRANSITION_MATRIX_ID", nullable = false,
insertable = true, updatable = true, length = 100)
private String TRANSITION_MATRIX_ID;
and put the #Id directly on the ManyToOne and remove the insertable and updateable attributes.
#Access(AccessType.FIELD)
#Id
#ManyToOne
#JoinColumn(name = "TRANSITION_MATRIX_ID", referencedColumnName = "ID_TRANSITION_MATRIX")
private MyLibraryTestEntity sabriEntity;
Update your ID class accordingly. Any previous reference to TRANSITION_MATRIX_ID should be replaced with a reference to sabriEntity. You are also confusing #EmbeddedId and #IdClass: Only the former would contain column definitions whereas you are using the latter approach.
public class MyLibrarySabriEntityPK implements Serializable {
private String sabriEntity;
private String RATING_ID_ROW;
private String RATING_ID_COL;
}
See:
https://en.wikibooks.org/wiki/Java_Persistence/Identity_and_Sequencing#JPA_2.0
Thank's to Alan Hay, I found the problem , I change the property TRANSITION_MATRIX_ID of my IDclass to sabriEntity and I delete all the annotation of this class !
Child entity
#Data
#Entity
#IdClass(MyLibrarySabriEntityPK.class)
#Table(name = "SABRI", schema = "L2S$OWNER", catalog = "")
public class MyLibrarySabriEntity extends ActionForm {
#Access(AccessType.FIELD)
#ManyToOne
#Id
#JoinColumn(name = "TRANSITION_MATRIX_ID", referencedColumnName = "ID_TRANSITION_MATRIX")
private MyLibraryTestEntity sabriEntity;
#Id
private String RATING_ID_ROW;
#Id
private String RATING_ID_COL;
#Basic
#Column(name = "TRANSITION_PROBABILITY", nullable = true, insertable = true, updatable = true, precision = 20)
private Double TRANSITION_PROBABILITY;
Parent Entity
#Data
#Entity
#Table(name = "TEST", schema = "L2S$OWNER", catalog = "")
public class MyLibraryTestEntity extends ActionForm {
#Access(AccessType.FIELD)
#OneToMany(mappedBy = "sabriEntity", cascade = CascadeType.PERSIST)
private final List<MyLibrarySabriEntity> entities = new ArrayList<MyLibrarySabriEntity>(25);
public void addEntitysabri(MyLibrarySabriEntity entity) {
getEntities().add(entity);
entity.setSabriEntity(this);
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO, generator = "IdGenerated")
#GenericGenerator(name = "IdGenerated", strategy = "dao.Identifier")
#Column(name = "ID_TRANSITION_MATRIX", nullable = false, insertable = false, updatable = false, length = 10)
private String ID_TRANSITION_MATRIX;
#Basic
#Column(name = "REFERENCE", nullable = true, insertable = true, updatable = true, precision = 0)
private Integer reference;
PK Class
#Data
public class MyLibrarySabriEntityPK implements Serializable {
private MyLibraryTestEntity sabriEntity;
private String RATING_ID_ROW;
private String RATING_ID_COL;
public MyLibrarySabriEntityPK() {
}
public MyLibrarySabriEntityPK(MyLibraryTestEntity sabriEntity,String RATING_ID_COL,String RATING_ID_ROW ){
this.sabriEntity=sabriEntity;
this.RATING_ID_COL = RATING_ID_COL;
this.RATING_ID_ROW= RATING_ID_ROW;
}
}

Transform MySQL select to Criteria API

I have the following select statement in MySQL (sorry for the column/tables names):
SELECT a1.* FROM A a1
LEFT JOIN A a2
ON a1.DD_ID = a2.DD_ID
and a1.PRD = a2.PRD
AND a1.VN < a2.VN
LEFT JOIN B bb
ON a1.id = cc.del_id
WHERE a2.DD_ID is null
AND bb.del_id is null;
Here are the entities:
#Entity
#Table(name = "A", uniqueConstraints = {
#UniqueConstraint(columnNames = {"DD_ID", "VN", "PRD"})})
public class A
implements Serializable
{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "ID", unique = true, nullable = false)
private Long id;
#Column(name = "VN", nullable = false)
private Short vn;
#Column(name = "PRD", nullable = false)
#NotNull
private String prd;
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "DD_ID", nullable = false)
#NotNull
private DD dd;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "A")
private Set<B> bs;
#Override
public boolean equals(final Object pOther)
{
...
}
#Override
public int hashCode()
{
...
}
// getters and setters
}
#Entity
#Table(name = "B")
public class B
implements Serializable
{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "ID", unique = true, nullable = false)
private Long id;
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "DEL_ID", nullable = false)
#NotNull
private A a;
#Override
public boolean equals(final Object pOther)
{
...
}
// getters and setters
}
and I want to implement it using Criteria API, but I have troubles implementing the self left join from the statement.
Any suggestions?

Why Select query incrementing #Version

The version for the class Application is getting incremented after the execution of the following statement
Queue queue = queueDao.fetchQueueByApplicationId(application.getApplicationId());
It is a simple fetch query only and it should not increment the version of the call any how. But after above line execution the version is getting incremented unexpectedly for Application class
Could someone please help
Thanks.
Queue.java
#Entity
#Table(name = "queue")
#NamedQuery(name = "queueByApplicationId", query = "SELECT q from Queue q WHERE q.application.applicationId = ?")
public class Queue implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "queue_id", unique = true, nullable = false)
private Long queueId;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "created", nullable = false, length = 19)
private Date created;
#Column(name = "created_by")
private Long createdBy;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "updated", length = 19)
private Date updated;
#Column(name = "updated_by")
private Long updatedBy;
#Version
#Column(name = "version", nullable = false)
private Integer version;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "application_id")
private Application application;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "queue", cascade = { CascadeType.PERSIST, CascadeType.MERGE })
private List<QueueAssignedToRole> queueAssignedToRoles;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "queue", cascade = { CascadeType.PERSIST, CascadeType.MERGE })
private List<QueueAssignedUser> queueAssignedUsers;
getter setter ....
}
Application.java
#Entity
#Table(name = "application")
public class Application implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private Long applicationId;
private Integer version;
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "application_id", unique = true, nullable = false)
public Long getApplicationId() {
return this.applicationId;
}
public void setApplicationId(Long applicationId) {
this.applicationId = applicationId;
}
#Version
#Column(name = "version", nullable = false)
public Integer getVersion() {
return this.version;
}
public void setVersion(Integer version) {
this.version = version;
}
}
ApplicationQueueDaoImpl.java
#Repository
public class ApplicationQueueDaoImpl extends AbstractDao<Queue> {
private static final Logger LOGGER = LogManager.getLogger(ApplicationQueueDaoImpl.class);
#Override
public Queue fetchQueueByApplicationId(Long applicationId) {
LOGGER.debug("Fetching Queue information for applicationId {}", applicationId);
List<Queue> queues = executeNamedQuery("queueByApplicationId", Queue.class, applicationId);
return CollectionUtils.isEmpty(queues) ? null : queues.get(0);
}
}
AbstractDao.java
protected <T> List<T> executeNamedQuery(String queryName, Class<T> resultType, Object... positionalParams) {
TypedQuery<T> query = entityManager.createNamedQuery(queryName, resultType);
DAOUtils.setPositionalParams(query, positionalParams);
return query.getResultList();
}

Categories