How to map database hql - java

I have database with 2 simple tables.
cat (category) with id, name.
prod (products) with id, catid, name, price.
I made a query
select pr.id, pr.catid,pr.name, pr.price
FROM prod pr, cat ct
WHERE pr.catid = ct.id AND ct.name = ?
I noticed problem eariler when I use #JoinColumn(name="catid") in prod class.
Repeated column in mapping for entity: goods.prod column: catid
(should be mapped with insert="false" update="false"
I try to use #JoinColumn(name="catid",insertable = false, updatable = false)
but even with this I have cast error.
Ljava.lang.Object; cannot be cast to goods.prod
How can I map database? And do I need to make changes in simplest SQL?
cat class
package goods;
import java.io.Serializable;
import java.util.List;
import java.util.ArrayList;
import goods.prod;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name="cat")
public class cat implements Serializable {
#Id
#Column(name="id",insertable = false, updatable = false)
private Integer id;
#OneToMany(mappedBy="catmap")
private List<prod> prods;
private static final long serialVersionUID = -4147058093508047162L;
private String name;
public cat() {
}
public cat(int id, String Name) {
this.id = id;
this.name = Name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String Name) {
this.name = Name;
}
}
prod class
package goods;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinColumns;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import goods.cat;
import java.io.Serializable;
#Entity
#Table(name = "prod")
public class prod implements Serializable {
#Id #GeneratedValue
#Column(name="id",insertable = false, updatable = false)
private Long id;
#ManyToOne (fetch=FetchType.LAZY)
#JoinColumn(name="catid",insertable = false, updatable = false)
private cat catmap;
private Integer catid;
private String name;
private Integer price;
public prod() {
}
public prod(Long id, Integer catid, String name, Integer price) {
this.id = id;
this.catid = catid;
this.name = name ;
this.price = price;
}
public Long getid() {
return id;
}
public void setid(Long id) {
this.id = id;
}
public Integer getcatid() {
return catid;
}
public void setcatid(Integer catid) {
this.catid = catid;
}
public String getname() {
return name;
}
public void setname(String name) {
this.name = name;
}
public Integer getprice() {
return price;
}
public void setprice(Integer price) {
this.price = price;
}
}
func
#SuppressWarnings("unchecked")
public static ArrayList<prod> getListOfProds(String catname,String name,Integer pricel, Integer priceh){
ArrayList<prod> list = new ArrayList<prod>();
Session session = HibernateUtil.openSession();
Transaction tx = null;
try {
tx = session.getTransaction();
tx.begin();
//Query query = session.createQuery("FROM prod");
Query query = session.createQuery("select pr.id, pr.catid,pr.name, pr.price FROM prod pr, cat ct WHERE pr.catid = ct.id AND ct.name = ?");
//Query query = session.createQuery("from prod pr join pr.cat ct with pr.catid=ct.id where ct.name=?");
query.setString(0, catname);
//query.setInteger(1, pricel);
//query.setInteger(2, priceh);
list = (ArrayList<prod>) query.list();
tx.commit();
} catch (Exception e) {
if (tx != null) {
tx.rollback();
}
e.printStackTrace();
} finally {
session.close();
}
return list;
}

Related

Why hibernate update after insert the record in table

I have two Entities CompanyDetail and DriverDetail
CompanyDetail
package com.javarnd.pns.model;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
#Entity
#Table(name="company_detail")
public class CompanyDetails {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="company_id")
private long companyId;
#Column(name="company_name")
private String companyName;
#Column(name="pan_no")
private String panNo;
private String website;
private String email;
#Column(name="conntact_no")
private String contactNo;
#OneToMany(cascade = CascadeType.ALL)
#LazyCollection(LazyCollectionOption.FALSE)
#JoinTable(name = "COMPANY_VEHICLE_DETAIL", joinColumns = #JoinColumn(name = "company_id"), inverseJoinColumns = #JoinColumn(name = "vehicle_id"))
private List<Vehicle> vehicleList;
#OneToMany(cascade = CascadeType.ALL)
#LazyCollection(LazyCollectionOption.FALSE)
#JoinTable(name = "COMPANY_DRIVER_DETAIL", joinColumns = #JoinColumn(name = "company_id"), inverseJoinColumns = #JoinColumn(name = "driver_id"))
private List<DriverDetail> driverList;
#Column(name="type")
private String companyType;
public long getCompanyId() {
return companyId;
}
public void setCompanyId(long companyId) {
this.companyId = companyId;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public String getPanNo() {
return panNo;
}
public void setPanNo(String panNo) {
this.panNo = panNo;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getContactNo() {
return contactNo;
}
public void setContactNo(String contactNo) {
this.contactNo = contactNo;
}
public String getCompanyType() {
return companyType;
}
public void setCompanyType(String companyType) {
this.companyType = companyType;
}
public List<Vehicle> getVehicleList() {
return vehicleList;
}
public void setVehicleList(List<Vehicle> vehicleList) {
this.vehicleList = vehicleList;
}
public List<DriverDetail> getDriverList() {
return driverList;
}
public void setDriverList(List<DriverDetail> driverList) {
this.driverList = driverList;
}
}
DriverDetail
package com.javarnd.pns.model;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;
import javax.persistence.OneToOne;
#Entity
public class DriverDetail {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="driver_id")
private long id;
private String name;
#Column(name="contact_no")
private String contactNo;
#Column(name="license_no")
private String licenseNo;
#ManyToMany(mappedBy="availableDriverList",cascade=CascadeType.ALL)
private List<Vehicle> asignedVehicle;
#OneToOne(cascade=CascadeType.ALL)
#JoinColumn(name="company_id")
private CompanyDetails companyDetail;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContactNo() {
return contactNo;
}
public String getLicenseNo() {
return licenseNo;
}
public void setLicenseNo(String licenseNo) {
this.licenseNo = licenseNo;
}
public List<Vehicle> getAsignedVehicle() {
return asignedVehicle;
}
public void setAsignedVehicle(List<Vehicle> asignedVehicle) {
this.asignedVehicle = asignedVehicle;
}
public CompanyDetails getCompanyDetail() {
return companyDetail;
}
public void setCompanyDetail(CompanyDetails companyDetail) {
this.companyDetail = companyDetail;
}
public void setContactNo(String contactNo) {
this.contactNo = contactNo;
}
}
MAIN TEST CLASS
package com.javarnd.pns.test;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import com.javarnd.pns.model.CompanyDetails;
import com.javarnd.pns.model.DriverDetail;
import com.javarnd.pns.service.CompanyDetailService;
import com.javarnd.pns.service.DriverDetailService;
public class TestPns {
public static void main(String[] args) {
CompanyDetailService cdService=new CompanyDetailService();
CompanyDetails cd=new CompanyDetails();
List<DriverDetail>ddList=new ArrayList<>();
DriverDetail driver=new DriverDetail();
DriverDetailService dds=new DriverDetailService();
Scanner kb=new Scanner(System.in);
System.out.println("Enter name:");
String cname=kb.nextLine();
driver.setName(cname);
System.out.println("Enter Compnay Id");
long companyId=kb.nextLong();
cd.setCompanyId(companyId);
System.out.println("Enter License:");
String license=kb.next();
driver.setLicenseNo(license);
System.out.println("Enter Contact");
String contact=kb.nextLine();
driver.setContactNo(contact);
ddList.add(driver);
cd.setDriverList(ddList);
driver.setCompanyDetail(cd);
dds.save(driver);
System.out.println("saved");
}
}
And now I tested that from my above main class, it printed the log in which it insert the values in DriverDetail table and update the company_detail table and at last then insert the values in COMPANY_DRIVER_DETAIL table
Finally the console LOG
Hibernate:
select
next_val as id_val
from
hibernate_sequence for update
Hibernate:
update
hibernate_sequence
set
next_val= ?
where
next_val=?
Hibernate:
/* insert com.javarnd.pns.model.DriverDetail
*/ insert
into
DriverDetail
(company_id, contact_no, license_no, name, driver_id)
values
(?, ?, ?, ?, ?)
Hibernate: //HERE IT IS UPDATING THE CompanyDetail , MAIKING ALL FIELDS NULL
/* update
com.javarnd.pns.model.CompanyDetails */ update
company_detail
set
company_name=?,
type=?,
conntact_no=?,
email=?,
pan_no=?,
website=?
where
company_id=?
Hibernate:
/* delete collection com.javarnd.pns.model.CompanyDetails.driverList */ delete
from
COMPANY_DRIVER_DETAIL
where
company_id=?
Hibernate:
/* delete collection com.javarnd.pns.model.CompanyDetails.vehicleList */ delete
from
COMPANY_VEHICLE_DETAIL
where
company_id=?
Hibernate:
/* insert collection
row com.javarnd.pns.model.CompanyDetails.driverList */ insert
into
COMPANY_DRIVER_DETAIL
(company_id, driver_id)
values
(?, ?)
After this everything goes fine except that the data corresponding of the particular id in Country_detail table is all NULL, and i don't want to fetch the data on behalf of id and then pass the object to driver.setCompanyDetail(cd); because it somehow degrades the performance, i need to know the way to resist this unnecessary update.

How to handle many-to-many relationship in Hibernate with non-primary key?

I have two objects - Role and Privilege. They have a many-to-many relationship. The code of each object is shown below.
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.NaturalId;
#Entity
#Table(name = "rml_privilege")
public class RmlPrivilege extends RmlBase implements Serializable{
/**
*
*/
private static final long serialVersionUID = -6810028565979325754L;
public static final String ATTR_NAME = "name";
#Column(name="name",nullable=false,unique=true)
private String name;
#Column(name="description")
private String description;
public String getName() {
return name;
}
public void setName(String privilege) {
this.name = privilege;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
This is the RmlRole file.
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name = "rml_role")
public class RmlRole extends RmlBase {
public final static String ATTR_ORG = "org.id";
#Column(name = "name")
private String name;
#Column(name = "description")
private String description;
#ManyToOne(fetch=FetchType.EAGER)
#JoinColumn(name = "organization")
private RmlOrganization organization;
//TODO: In case of LAZY loading, recieve an error
#ManyToMany(cascade=CascadeType.PERSIST,fetch=FetchType.EAGER)
#JoinTable(name = "rml_role_privilege", joinColumns = {
#JoinColumn(name = "role", referencedColumnName = "id") }, inverseJoinColumns = {
#JoinColumn(name = "privilege", referencedColumnName = "name") })
Set<RmlPrivilege> privileges;
public RmlOrganization getOrganization() {
return organization;
}
public void setOrganization(RmlOrganization organization) {
this.organization = organization;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Set<RmlPrivilege> getPrivileges() {
return privileges;
}
public void setPrivileges(Set<RmlPrivilege> privileges) {
this.privileges = privileges;
}
}
When I try to get the RmlRole object, I end up getting the "privileges' variable to be blank. I expect the privilege object set to be prepared. I am doing it wrong somewhere but unable to identify.
My Hibernate version: 5
Java 1.8
Spring Boot application
Any help would be highly appreciated.

Hibernate Use of #OneToMany or #ManyToMany targeting an unmapped class

I have read so much topics and still I cant solve my problem.
Problem: error from title. I get it every time I try to read entity from database.
Database is mysql one, connected by jdbc driver.
Here is my code: First one is ReadStudentDemo (to read from database)
package entities;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.persistence.EntityTransaction;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class ReadStudentDemo {
public static void main(String[] args) throws ParseException {
Player roggy = new Player();
Configuration conf = new Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(Player.class);
ServiceRegistry sr = new StandardServiceRegistryBuilder().applySettings(conf.getProperties()).build();
SessionFactory sf = conf.buildSessionFactory(sr);
Session session = sf.openSession();
EntityTransaction tx = session.beginTransaction();
roggy = (Player)session.get(Player.class, 4);
tx.commit();
System.out.println(roggy);
}
}
second is Player.java with Player entity mapped.
package entities;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* Player generated by hbm2java
*/
#Entity
#Table(name = "Player", catalog = "sql11217012")
public class Player implements java.io.Serializable {
private Integer id;
private String firstName;
private String lastName;
private Date birth;
private Float wl;
private Integer win;
private BigDecimal money;
private Set<Match> matchesForPlayerId = new HashSet<Match>(0);
private Set<Match> matchesForPlayer1Id = new HashSet<Match>(0);
private Set<Match> matchesForCourtId = new HashSet<Match>(0);
public Player() {
}
public Player(String firstName, String lastName, Date birth, Float wl, Integer win, BigDecimal money,
Set<Match> matchesForPlayerId, Set<Match> matchesForPlayer1Id, Set<Match> matchesForCourtId) {
this.firstName = firstName;
this.lastName = lastName;
this.birth = birth;
this.wl = wl;
this.win = win;
this.money = money;
this.matchesForPlayerId = matchesForPlayerId;
this.matchesForPlayer1Id = matchesForPlayer1Id;
this.matchesForCourtId = matchesForCourtId;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "first_name", length = 45)
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Column(name = "last_name", length = 45)
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Temporal(TemporalType.DATE)
#Column(name = "birth", length = 10)
public Date getBirth() {
return this.birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
#Column(name = "wl", precision = 12, scale = 0)
public Float getWl() {
return this.wl;
}
public void setWl(Float wl) {
this.wl = wl;
}
#Column(name = "win")
public Integer getWin() {
return this.win;
}
public void setWin(Integer win) {
this.win = win;
}
#Column(name = "money", precision = 15)
public BigDecimal getMoney() {
return this.money;
}
public void setMoney(BigDecimal money) {
this.money = money;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "playerByPlayerId")
public Set<Match> getMatchesForPlayerId() {
return this.matchesForPlayerId;
}
public void setMatchesForPlayerId(Set<Match> matchesForPlayerId) {
this.matchesForPlayerId = matchesForPlayerId;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "playerByPlayer1Id")
public Set<Match> getMatchesForPlayer1Id() {
return this.matchesForPlayer1Id;
}
public void setMatchesForPlayer1Id(Set<Match> matchesForPlayer1Id) {
this.matchesForPlayer1Id = matchesForPlayer1Id;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "playerByCourtId")
public Set<Match> getMatchesForCourtId() {
return this.matchesForCourtId;
}
public void setMatchesForCourtId(Set<Match> matchesForCourtId) {
this.matchesForCourtId = matchesForCourtId;
}
}
Then you have Match entity.
package entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name = "Match", catalog = "sql11217012")
public class Match implements java.io.Serializable {
private Integer id;
private Player playerByPlayerId;
private Player playerByPlayer1Id;
private Player playerByCourtId;
public Match() {
}
public Match(Player playerByPlayerId, Player playerByPlayer1Id, Player playerByCourtId) {
this.playerByPlayerId = playerByPlayerId;
this.playerByPlayer1Id = playerByPlayer1Id;
this.playerByCourtId = playerByCourtId;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "player_id", nullable = false)
public Player getPlayerByPlayerId() {
return this.playerByPlayerId;
}
public void setPlayerByPlayerId(Player playerByPlayerId) {
this.playerByPlayerId = playerByPlayerId;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "player1_id", nullable = false)
public Player getPlayerByPlayer1Id() {
return this.playerByPlayer1Id;
}
public void setPlayerByPlayer1Id(Player playerByPlayer1Id) {
this.playerByPlayer1Id = playerByPlayer1Id;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "court_id", nullable = false)
public Player getPlayerByCourtId() {
return this.playerByCourtId;
}
public void setPlayerByCourtId(Player playerByCourtId) {
this.playerByCourtId = playerByCourtId;
}
}
And then the stack trace
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Exception in thread "main" org.hibernate.AnnotationException: Use of #OneToMany or #ManyToMany targeting an unmapped class: entities.Player.matchesForCourtId[entities.Match]
at org.hibernate.cfg.annotations.CollectionBinder.bindManyToManySecondPass(CollectionBinder.java:1253)
at org.hibernate.cfg.annotations.CollectionBinder.bindStarToManySecondPass(CollectionBinder.java:810)
at org.hibernate.cfg.annotations.CollectionBinder$1.secondPass(CollectionBinder.java:735)
at org.hibernate.cfg.CollectionSecondPass.doSecondPass(CollectionSecondPass.java:54)
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses(InFlightMetadataCollectorImpl.java:1621)
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses(InFlightMetadataCollectorImpl.java:1589)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:278)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:83)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:418)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:87)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:691)
at entities.ReadStudentDemo.main(ReadStudentDemo.java:50)
Thanks in advance for any help!
Well you add Player to your Configuration
Configuration conf = new Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(Player.class);
but seems you never add Match.class?
So probably you should use
Configuration conf = new Configuration()
.configure("hibernate.cfg.xml")
.addAnnotatedClass(Player.class)
.addAnnotatedClass(Match.class);

How Filter data When key attribute is in child Table +spring mvc and hibernate

There are 2 table, Parent is MeetingTypes Child is Meetings they have1 : m mapping
Meeting has releaseID atribute so i want to filter its by releaseID .but problem is, its in Child Table...
If it is Parent Table we can do it simply and it is working
Query query = session.getCurrentSession().createQuery("from MeetingTypes where releaseID= :releaseID");
query.setParameter("releaseID", releaseID);
List list = query.list();
if(list!=null && list.size()>0){
return list;
}else{
return null;
}
I tried it this way
Query query = session.getCurrentSession().createSQLQuery(
"from MeetingTypes mt join mt.Meetings m " +
"where m.releaseID = :releaseID");
query.setParameter("releaseID", releaseID);
return query.list();
But give bellow Erro
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'from MeetingTypes mt join mt.Meetings m where m.releaseID = 192' at
line 1
relevant tabales
package pearson.dashboard.model;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
#Entity
public class MeetingTypes {
#Id
#Column
#GeneratedValue(strategy=GenerationType.AUTO)
private int meetingTypeID;
#Column
private String typeName;
#OneToMany(mappedBy = "meetingTypes",fetch = FetchType.EAGER)
private List<Meetings> meetings;
public List<Meetings> getMeetings() {
return meetings;
}
public void setMeetings(List<Meetings> meetings) {
this.meetings = meetings;
}
public MeetingTypes() {
// TODO Auto-generated constructor stub
}
public MeetingTypes(int meetingTypeID, String typeName
) {
super();
this.meetingTypeID = meetingTypeID;
this.typeName = typeName;
}
public int getMeetingTypeID() {
return meetingTypeID;
}
public void setMeetingTypeID(int meetingTypeID) {
this.meetingTypeID = meetingTypeID;
}
public String getTypeName() {
return typeName;
}
public void setTypeName(String typeName) {
this.typeName = typeName;
}
}
package pearson.dashboard.model;
import java.util.Date;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import org.springframework.context.annotation.Lazy;
#Entity
public class Meetings {
#Id
#Column
#GeneratedValue(strategy=GenerationType.AUTO)
private int meetingID;
#Column
private Date sheduleTime;
#Column
private String meetingHeading;
#Column
private String comment;
#Column
private String roomName;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "meetingTypeID")
private MeetingTypes meetingTypes;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "releaseID")
private Releases releases;
public Releases getReleases() {
return releases;
}
public void setReleases(Releases releases) {
this.releases = releases;
}
public MeetingTypes getMeetingTypes() {
return meetingTypes;
}
public void setMeetingTypes(MeetingTypes meetingTypes) {
this.meetingTypes = meetingTypes;
}
public Meetings() {
// TODO Auto-generated constructor stub
}
public Meetings(int meetingID, Date sheduleTime, String meetingHeading,
String comment, String roomName) {
super();
this.meetingID = meetingID;
this.sheduleTime = sheduleTime;
this.meetingHeading = meetingHeading;
this.comment = comment;
this.roomName = roomName;
}
public int getMeetingID() {
return meetingID;
}
public void setMeetingID(int meetingID) {
this.meetingID = meetingID;
}
public Date getSheduleTime() {
return sheduleTime;
}
public void setSheduleTime(Date sheduleTime) {
this.sheduleTime = sheduleTime;
}
public String getMeetingHeading() {
return meetingHeading;
}
public void setMeetingHeading(String meetingHeading) {
this.meetingHeading = meetingHeading;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getRoomName() {
return roomName;
}
public void setRoomName(String roomName) {
this.roomName = roomName;
}
}
package pearson.dashboard.model;
import java.util.Date;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
#Entity
public class Releases {
#Id
#Column
#GeneratedValue(strategy=GenerationType.AUTO)
private int releaseID;
#Column
private String orcleCode;
#Column
private String status;
#Column
private Date staging;
#Column
private Date cabCall;
#Column
private Date rrr;
#Column
private String remarks;
#Column
private String releaseName;
#Column
private Date prodDate;
#ManyToOne( fetch = FetchType.EAGER)
#JoinColumn(name = "teamID")
private Teams teams;
public Teams getTeams() {
return teams;
}
public void setTeams(Teams teams) {
this.teams = teams;
}
#OneToMany(mappedBy = "releases",fetch = FetchType.EAGER)
#Fetch(value = FetchMode.SUBSELECT)
private List<Meetings> meetings;
public List<Meetings> getMeetings() {
return meetings;
}
public void setMeetings(List<Meetings> meetings) {
this.meetings = meetings;
}
public Releases() {}
public Releases(int releasID, String orcleCode, String status,
Date staging, Date cabCall, Date rrr, String remarks,
String releaseName,Date prodDate) {
super();
this.releaseID = releasID;
this.orcleCode = orcleCode;
this.status = status;
this.staging = staging;
this.cabCall = cabCall;
this.rrr = rrr;
this.remarks = remarks;
this.releaseName = releaseName;
this.prodDate = prodDate;
}
public int getReleaseID() {
return releaseID;
}
public void setReleaseID(int releaseID) {
this.releaseID = releaseID;
}
public String getOrcleCode() {
return orcleCode;
}
public void setOrcleCode(String orcleCode) {
this.orcleCode = orcleCode;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Date getStaging() {
return staging;
}
public void setStaging(Date staging) {
this.staging = staging;
}
public Date getCabCall() {
return cabCall;
}
public void setCabCall(Date cabCall) {
this.cabCall = cabCall;
}
public Date getRrr() {
return rrr;
}
public void setRrr(Date rrr) {
this.rrr = rrr;
}
public String getRemarks() {
return remarks;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
public String getReleaseName() {
return releaseName;
}
public void setReleaseName(String releaseName) {
this.releaseName = releaseName;
}
public Date getProdDate() {
return prodDate;
}
public void setProdDate(Date prodDate) {
this.prodDate = prodDate;
}
}
part of Controller******
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import pearson.dashboard.dto.NewMeeting;
import pearson.dashboard.service.MeetingService;
import pearson.dashboard.service.MeetingTypeService;
import pearson.dashboard.service.MemberService;
import pearson.dashboard.service.SwarmingScheduleService;
#Controller
public class MeetingTypesController {
#Autowired
private MeetingTypeService meetingTypeService;
//#Autowired
//private MeetingService meetingService;
#Autowired
private SwarmingScheduleService swarmingScheduleService;
#Autowired
private MemberService memberService;
#RequestMapping(value="/detailsPage",method=RequestMethod.POST)
public String getAllmeeting(#ModelAttribute NewMeeting newMeeting,BindingResult result,Map<String, Object> map){
int releaseID = newMeeting.getReleaseID();
map.put("meetingList", meetingTypeService.getAllMeetingTypes(releaseID));
map.put("swarmingScheduleList",swarmingScheduleService.gettAllSwarming() );
map.put("memberList",memberService.gettAllMembers() );
return "details";
}
}
You are using HQL not sql so in hql no keyword like join alternatively you can implement join using objecta.objectb and so on so you have to create your query like below
Query query = session.getCurrentSession().createQuery("FROM MeetingTypes mt WHERE mt.meetings.releases.id = :releaseID");
for more details see the below link
http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/queryhql.html#queryhql-joins-forms
Your HQL query should be like this
Query query = session.getCurrentSession().createQuery("FROM MeetingTypes AS mt WHERE mt.meetings.releases.id = :releaseID");
query.setParameter("releaseID", releaseID);
return query.list();
hope this will solve your problem.
hopefully your Releases Entity something like
#Entity
#Table(name="meetings")
public class Meetings {
#Id
#Column(name="meetings_id")
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
//setter & getters
}
also you have not mentioned your name parameter in #Table() annotation is your table name is same as class name ?
#Entity
The #Entity annotation is used to mark this class as an Entity bean. So the class should atleast have a package scope no-argument constructor.
#Column
The #Column annotation is used to specify the details of the column to which a field or property will be mapped. If the #Column annotation is not specified by default the property name will be used as the column name.
#Table
The #Table annotation is used to specify the table to persist the data. The name attribute refers to the table name. If #Table annotation is not specified then Hibernate will by default use the class name as the table name.
createQuery() VS createSQLQuery()
createQuery()
Create a new instance of Query for the given HQL query string.
createSQLQuery()
Create a new instance of SQLQuery for the given SQL query string.

Cannot create a ManyToMany relationship between two entites

As I referenced in the title I have two entities in google app engine project. The first one is "store" and the other is "product". Before adding the ManyToMany annotation the entities stored regularly but after the relationship addition the entities cannot be stored even though there is a successful message returned!!
Here are the entities:
Store.java
package com.cheapchase.server;
import java.util.Date;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.JoinTable;
import javax.persistence.JoinColumn;
import javax.persistence.UniqueConstraint;
#Entity
#Table(name="store", catalog="content", uniqueConstraints={
#UniqueConstraint(columnNames = "STORE_NAME"),
#UniqueConstraint(columnNames = "STORE_CODE")})
public class Store{
private int storeCode;
private Date dueDate;
private String emailAddress;
private String storeName;
private String storeAddress;
private String storeDescription;
private String userId;
private Long id;
private Set<Product> product;
public Store(){
}
public Store(String storeName, int storeCode){
this.storeName = storeName;
this.setStoreCode(storeCode);
}
public Store(String storeName, int storeCode, Set<Product> product){
this.storeName = storeName;
this.storeCode = storeCode;
this.product = product;
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "STORE_ID", unique = true, nullable = false)
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
#Column(name="STORE_NAME", nullable=false)
public String getStoreName() {
return this.storeName;
}
public void setStoreName(String storeName) {
this.storeName = storeName;
}
/*
* Define the Many To Many relationship with product
*/
#ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinTable(name = "storae_product", catalog = "content", joinColumns = {
#JoinColumn(name = "STORE_ID", nullable = false)},
inverseJoinColumns = {#JoinColumn(name = "PRODUCT_ID", nullable = false)})
public Set<Product> getProduct(){
return this.product;
}
public void setProduct(Set<Product> product){
this.product = product;
}
/*
* Define the rest getters and setters
*/
public Date getDueDate() {
return dueDate;
}
public void setDueDate(Date dueDate) {
this.dueDate = dueDate;
}
public String getEmailAddress() {
return this.emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public String getStoreDescription() {
return storeDescription;
}
public void setStoreDescription(String storeDescription) {
this.storeDescription = storeDescription;
}
public String getStoreAddress() {
return storeAddress;
}
public void setStoreAddress(String storeAddress) {
this.storeAddress = storeAddress;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public int getStoreCode() {
return storeCode;
}
public void setStoreCode(int storeCode) {
this.storeCode = storeCode;
}
public String toString(){
StringBuilder builder = new StringBuilder();
builder.append("Store [dueDate=");
builder.append(dueDate);
builder.append(", name=");
builder.append(storeName);
builder.append(", description=");
builder.append(storeDescription);
builder.append("]");
return builder.toString();
}
}
Product.java
package com.cheapchase.server;
import java.util.Set;
import java.util.HashSet;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.Column;
import com.google.appengine.api.datastore.Blob;
#Entity
#Table(name = "product", catalog = "content")
public class Product {
private Long productId;
private String name;
private String description;
private int barCode;
Blob image;
private Set<Store> stores = new HashSet<Store>(0);
public Product(){
}
public Product(String name, String description){
this.name = name;
this.description = description;
}
public Product(String name, String description, Set<Store> stores){
this.name = name;
this.description = description;
this.stores = stores;
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "PRODUCT_ID", unique = true, nullable = false)
public Long getProductId(){
return this.productId;
}
public void setProductId(Long productId){
this.productId = productId;
}
#Column(name = "NAME", nullable = false)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
#Column(name = "DESCRIPTION")
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
#ManyToMany(fetch = FetchType.LAZY, mappedBy = "product")
public Set<Store> getStore(){
return this.stores;
}
public void setStore(Set<Store> store){
this.stores = store;
}
public int getBarCode() {
return barCode;
}
public void setBarCode(int barCode) {
this.barCode = barCode;
}
}

Categories

Resources