Persisting OneToMany relationship only persists first object in set? - java

Been messing around with Hibernate and PostgreSQL trying to get it to work as expected.
But for some reason when I try to persist an object with a #OneToMany relationship with more than one item in the set all but the first item seem to be ignored. I've tried this via local and remote interfaces but get the same results each time. No exceptions are thrown, it looks like hibernate just stops persisting after the first unit has been persisted.
Any help much appreciated this one has been eluding me for days now.
I'm using Hibernate 3.5 and PostgreSQL 8.4.4 with Glassfish v3. All the annotations in the source are from the package javax.persistence - had to remove imports because of the character limit.
The FacadeManager is simply a utility to take the hassle out of jndi lookups, it simplifies accessing remote facades.
Here is the test method
#Test
public void testOneToManyCascade() throws Exception {
/*
* Set up entities requred to perform the test
*/
UnitFacadeRemote unitfr = FacadeManager
.getFacade(UnitFacadeRemote.class);
UserFacadeRemote userfr = FacadeManager
.getFacade(UserFacadeRemote.class);
User user = new User("P", "P", "000000", true, new Date(), "ypy#ypy",
"wordof mout", "slacker", "password");
Address address = new Address("yo", "go", "YOKO", "4123");
address.setCountry(FacadeManager.getFacade(CountryFacadeRemote.class)
.find(2));
user.setAddress(address);
Unit unit1 = new Unit(1, "Test Unit1", new Date(), "DisService",
"MyNation");
Unit unit2 = new Unit(2, "Test Unit2", new Date(), "DisService",
"TheirNation");
Unit unit3 = new Unit(3, "Test Unit3", new Date(), "DisService",
"TheirNation");
// Check no game exists
assertThat(FacadeManager.getFacade(GameFacadeRemote.class).findAll()
.size(), is(0));
Game game = new Game("blabla", 3333, "A game!", true);
// Create game and return reference to persisted game instance
game = FacadeManager.getFacade(GameFacadeRemote.class).registerGame(
game);
unit1.setGame(game);
unit2.setGame(game);
unit3.setGame(game);
// Find a virtue
Virtue v = FacadeManager.getFacade(VirtueFacadeRemote.class).find(1);
unit1.setVirtue(v);
unit2.setVirtue(v);
unit3.setVirtue(v);
// check that none of the above exist already
assertThat(userfr.findAll().size(), is(0));
assertThat(unitfr.findAll().size(), is(0));
/*
* Try persisting the by cascading from the user
*/
Set<Unit> unitSet = new HashSet<Unit>();
unitSet.add(unit2);
unitSet.add(unit1);
unitSet.add(unit3);
user.setUnitSet(unitSet);
unit1.setUser(user);
unit2.setUser(user);
unit3.setUser(user);
// Persist
userfr.create(user);
/*
* The result of the preceding persist is that the game, user, address
* and one unit are persisted, in this case unit2 but it seems whichever
* unit is first added to unitSet is the one that is persisted.
*/
}
Here follow the various entity classes
package com.game.database.entity;
#Entity
#Table(name = "address")
#NamedQueries({
#NamedQuery(name = "Address.findAll", query = "SELECT a FROM Address a"),
#NamedQuery(name = "Address.findById", query = "SELECT a FROM Address a WHERE a.id = :id"),
#NamedQuery(name = "Address.findByLine1", query = "SELECT a FROM Address a WHERE a.line1 = :line1"),
#NamedQuery(name = "Address.findByLine2", query = "SELECT a FROM Address a WHERE a.line2 = :line2"),
#NamedQuery(name = "Address.findByCity", query = "SELECT a FROM Address a WHERE a.city = :city"),
#NamedQuery(name = "Address.findByAreaCode", query = "SELECT a FROM Address a WHERE a.areaCode = :areaCode") })
public class Address implements Serializable {
private static final long serialVersionUID = 1L;
#SequenceGenerator(name = "address_id_seq", sequenceName = "address_id_seq", allocationSize = 1)
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "address_id_seq")
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#Column(name = "line1")
private String line1;
#Basic(optional = false)
#Column(name = "line2")
private String line2;
#Basic(optional = false)
#Column(name = "city")
private String city;
#Basic(optional = false)
#Column(name = "areaCode")
private String areaCode;
#JoinColumn(name = "country", referencedColumnName = "id")
#ManyToOne(optional = false)
private Country country;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "address")
private Set<User> userSet;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "address")
private Set<CardDetails> cardDetailsSet;
public Address() {
}
public Address(Integer id) {
this.id = id;
}
public Address(String line1, String line2, String city, String areaCode) {
this.line1 = line1;
this.line2 = line2;
this.city = city;
this.areaCode = areaCode;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLine1() {
return line1;
}
public void setLine1(String line1) {
this.line1 = line1;
}
public String getLine2() {
return line2;
}
public void setLine2(String line2) {
this.line2 = line2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getAreaCode() {
return areaCode;
}
public void setAreaCode(String areaCode) {
this.areaCode = areaCode;
}
public Country getCountry() {
return country;
}
public void setCountry(Country country) {
this.country = country;
}
public Set<User> getUserSet() {
return userSet;
}
public void setUserSet(Set<User> userSet) {
this.userSet = userSet;
}
public Set<CardDetails> getCardDetailsSet() {
return cardDetailsSet;
}
public void setCardDetailsSet(Set<CardDetails> cardDetailsSet) {
this.cardDetailsSet = cardDetailsSet;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are
// not set
if (!(object instanceof Address)) {
return false;
}
Address other = (Address) object;
if ((this.id == null && other.id != null)
|| (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.game.database.entity.Address[id=" + id + "]";
}
}
--
package com.game.database.entity;
#Entity
#Table(name = "game")
#NamedQueries({
#NamedQuery(name = "Game.findAll", query = "SELECT g FROM Game g"),
#NamedQuery(name = "Game.findById", query = "SELECT g FROM Game g WHERE g.id = :id"),
#NamedQuery(name = "Game.findByHost", query = "SELECT g FROM Game g WHERE g.host = :host"),
#NamedQuery(name = "Game.findByPort", query = "SELECT g FROM Game g WHERE g.port = :port"),
#NamedQuery(name = "Game.findByDescription", query = "SELECT g FROM Game g WHERE g.description = :description"),
#NamedQuery(name = "Game.findByActive", query = "SELECT g FROM Game g WHERE g.active = :active"),
#NamedQuery(name = "Game.findByHostAndPort", query = "SELECT g FROM Game g WHERE g.host = :host AND g.port = :port") })
public class Game implements Serializable {
private static final long serialVersionUID = 1L;
#SequenceGenerator(name = "game_id_seq", sequenceName = "game_id_seq", allocationSize = 1)
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "game_id_seq")
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#Column(name = "host")
private String host;
#Basic(optional = false)
#Column(name = "port")
private int port;
#Basic(optional = false)
#Column(name = "description")
private String description;
#Basic(optional = false)
#Column(name = "active")
private Boolean active;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "game")
private Set<Unit> unitSet;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "game")
private Set<Payment> paymentSet;
public Game() {
}
public Game(Integer id) {
this.id = id;
}
public Game(String host, int port, String description, Boolean active) {
this.host = host;
this.port = port;
this.description = description;
this.active = active;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Boolean getActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
public Set<Unit> getUnitSet() {
return unitSet;
}
public void setUnitSet(Set<Unit> unitSet) {
this.unitSet = unitSet;
}
public Set<Payment> getPaymentSet() {
return paymentSet;
}
public void setPaymentSet(Set<Payment> paymentSet) {
this.paymentSet = paymentSet;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are
// not set
if (!(object instanceof Game)) {
return false;
}
Game other = (Game) object;
if ((this.id == null && other.id != null)
|| (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.game.database.entity.Game[id=" + id + "]";
}
}
--
package com.game.database.entity;
#Entity
#Table(name = "unit")
#NamedQueries({
#NamedQuery(name = "Unit.findAll", query = "SELECT u FROM Unit u"),
#NamedQuery(name = "Unit.findById", query = "SELECT u FROM Unit u WHERE u.id = :id"),
#NamedQuery(name = "Unit.findByUnitId", query = "SELECT u FROM Unit u WHERE u.unitId = :unitId"),
#NamedQuery(name = "Unit.findByName", query = "SELECT u FROM Unit u WHERE u.name = :name"),
#NamedQuery(name = "Unit.findByRegistrationDate", query = "SELECT u FROM Unit u WHERE u.registrationDate = :registrationDate"),
#NamedQuery(name = "Unit.findByService", query = "SELECT u FROM Unit u WHERE u.service = :service"),
#NamedQuery(name = "Unit.findByNation", query = "SELECT u FROM Unit u WHERE u.nation = :nation") })
public class Unit implements Serializable {
private static final long serialVersionUID = 1L;
#SequenceGenerator(name = "unit_id_seq", sequenceName = "unit_id_seq", allocationSize = 1)
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "unit_id_seq")
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#Column(name = "unitId")
private Integer unitId;
#Basic(optional = false)
#Column(name = "name")
private String name;
#Basic(optional = false)
#Column(name = "registrationDate")
#Temporal(TemporalType.TIMESTAMP)
private Date registrationDate;
#Basic(optional = false)
#Column(name = "service")
private String service;
#Basic(optional = false)
#Column(name = "nation")
private String nation;
#JoinColumn(name = "virtue", referencedColumnName = "id")
#ManyToOne(optional = false)
private Virtue virtue;
#JoinColumn(name = "customer", referencedColumnName = "id")
#ManyToOne(optional = false)
private User customer;
#JoinColumn(name = "game", referencedColumnName = "id")
#ManyToOne(optional = false)
private Game game;
public Unit() {
}
public Unit(Integer id) {
this.id = id;
}
public Unit(Integer unitId, String name, Date registrationDate,
String service, String nation) {
this.unitId = unitId;
this.name = name;
this.registrationDate = registrationDate;
this.service = service;
this.nation = nation;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getUnitId() {
return unitId;
}
public void setUnitId(Integer unitId) {
this.unitId = unitId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getRegistrationDate() {
return registrationDate;
}
public void setRegistrationDate(Date registrationDate) {
this.registrationDate = registrationDate;
}
public String getService() {
return service;
}
public void setService(String service) {
this.service = service;
}
public String getNation() {
return nation;
}
public void setNation(String nation) {
this.nation = nation;
}
public Virtue getVirtue() {
return virtue;
}
public void setVirtue(Virtue virtue) {
this.virtue = virtue;
}
public User getUser() {
return customer;
}
public void setUser(User user) {
this.customer = user;
}
public Game getGame() {
return game;
}
public void setGame(Game game) {
Logger.getLogger("org.hibernate").setLevel(Level.FINEST);
this.game = game;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are
// not set
if (!(object instanceof Unit)) {
return false;
}
Unit other = (Unit) object;
if ((this.id == null && other.id != null)
|| (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.game.database.entity.Unit[id=" + id + "]";
}
#Transient
private String command;
/**
* Get the value of command
*
* #return the value of command
*/
public String getCommand() {
return command;
}
/**
* Set the value of command
*
* #param command
* new value of command
*/
public void setCommand(String command) {
this.command = command;
}
#Transient
private String rank;
/**
* Get the value of rank
*
* #return the value of rank
*/
public String getRank() {
return rank;
}
/**
* Set the value of rank
*
* #param rank
* new value of rank
*/
public void setRank(String rank) {
this.rank = rank;
}
#Transient
private BigDecimal price;
/**
* Get the value of price
*
* #return the value of price
*/
public BigDecimal getPrice() {
return price;
}
/**
* Set the value of price
*
* #param price
* new value of price
*/
public void setPrice(BigDecimal price) {
this.price = price;
}
}
--
package com.game.database.entity;
#Entity
#Table(name = "customer")
#NamedQueries({
#NamedQuery(name = "User.findAll", query = "SELECT u FROM User u"),
#NamedQuery(name = "User.findById", query = "SELECT u FROM User u WHERE u.id = :id"),
#NamedQuery(name = "User.findByGivenName", query = "SELECT u FROM User u WHERE u.givenName = :givenName"),
#NamedQuery(name = "User.findBySurname", query = "SELECT u FROM User u WHERE u.surname = :surname"),
#NamedQuery(name = "User.findByPhoneNumber", query = "SELECT u FROM User u WHERE u.phoneNumber = :phoneNumber"),
#NamedQuery(name = "User.findBySex", query = "SELECT u FROM User u WHERE u.sex = :sex"),
#NamedQuery(name = "User.findByBirthYear", query = "SELECT u FROM User u WHERE u.birthYear = :birthYear"),
#NamedQuery(name = "User.findByEmail", query = "SELECT u FROM User u WHERE u.email = :email"),
#NamedQuery(name = "User.findByInfoSource", query = "SELECT u FROM User u WHERE u.infoSource = :infoSource"),
#NamedQuery(name = "User.findByOccupation", query = "SELECT u FROM User u WHERE u.occupation = :occupation"),
#NamedQuery(name = "User.findByPassword", query = "SELECT u FROM User u WHERE u.password = :password"),
#NamedQuery(name = "User.findByEmailAndPassword", query = "SELECT u FROM User u WHERE u.password = :password AND u.email = :email") })
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#SequenceGenerator(name = "user_id_seq", sequenceName = "user_id_seq", allocationSize = 1)
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_id_seq")
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#Column(name = "givenName")
private String givenName;
#Basic(optional = false)
#Column(name = "surname")
private String surname;
#Basic(optional = false)
#Column(name = "phoneNumber")
private String phoneNumber;
#Basic(optional = false)
#Column(name = "sex")
private boolean sex;
#Basic(optional = false)
#Column(name = "birthYear")
#Temporal(TemporalType.DATE)
private Date birthYear;
#Basic(optional = false)
#Column(name = "email")
private String email;
#Basic(optional = false)
#Column(name = "infoSource")
private String infoSource;
#Basic(optional = false)
#Column(name = "occupation")
private String occupation;
#Basic(optional = false)
#Column(name = "password")
private String password;
/**
* The EAGER fetch type ensures that when we get access a unit remotely it
* has had its unit set initialised and populated
*/
#OneToMany(cascade = CascadeType.ALL, mappedBy = "customer", fetch = FetchType.EAGER)
private Set<Unit> unitSet;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "customer", fetch = FetchType.EAGER)
private Set<Payment> paymentSet;
#JoinColumn(name = "address", referencedColumnName = "id")
#ManyToOne(cascade = CascadeType.ALL, optional = false)
private Address address;
public User() {
}
public User(Integer id) {
this.id = id;
}
public User(String givenName, String surname, String phoneNumber,
boolean sex, Date birthYear, String email, String infoSource,
String occupation, String password) {
this.givenName = givenName;
this.surname = surname;
this.phoneNumber = phoneNumber;
this.sex = sex;
this.birthYear = birthYear;
this.email = email;
this.infoSource = infoSource;
this.occupation = occupation;
this.password = password;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getGivenName() {
return givenName;
}
public void setGivenName(String givenName) {
this.givenName = givenName;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public boolean getSex() {
return sex;
}
public void setSex(boolean sex) {
this.sex = sex;
}
public Date getBirthYear() {
return birthYear;
}
public void setBirthYear(Date birthYear) {
this.birthYear = birthYear;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getInfoSource() {
return infoSource;
}
public void setInfoSource(String infoSource) {
this.infoSource = infoSource;
}
public String getOccupation() {
return occupation;
}
public void setOccupation(String occupation) {
this.occupation = occupation;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Set<Unit> getUnitSet() {
return unitSet;
}
public void setUnitSet(Set<Unit> unitSet) {
this.unitSet = unitSet;
}
public Set<Payment> getPaymentSet() {
return paymentSet;
}
public void setPaymentSet(Set<Payment> paymentSet) {
this.paymentSet = paymentSet;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are
// not set
if (!(object instanceof User)) {
return false;
}
User other = (User) object;
if ((this.id == null && other.id != null)
|| (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.game.database.entity.User[id=" + id + "]";
}
}
--
package com.game.database.entity;
#Entity
#Table(name = "virtue")
#NamedQueries({
#NamedQuery(name = "Virtue.findAll", query = "SELECT v FROM Virtue v"),
#NamedQuery(name = "Virtue.findById", query = "SELECT v FROM Virtue v WHERE v.id = :id"),
#NamedQuery(name = "Virtue.findByName", query = "SELECT v FROM Virtue v WHERE v.name = :name"),
#NamedQuery(name = "Virtue.findByDescription", query = "SELECT v FROM Virtue v WHERE v.description = :description") })
public class Virtue implements Serializable {
private static final long serialVersionUID = 1L;
#SequenceGenerator(name = "virtue_id_seq", sequenceName = "virtue_id_seq", allocationSize = 1)
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "virtue_id_seq")
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#Column(name = "name")
private String name;
#Basic(optional = false)
#Column(name = "description")
private String description;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "virtue")
private Set<Unit> unitSet;
public Virtue() {
}
public Virtue(Integer id) {
this.id = id;
}
public Virtue(String name, String description) {
this.name = name;
this.description = description;
}
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;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Set<Unit> getUnitSet() {
return unitSet;
}
public void setUnitSet(Set<Unit> unitSet) {
this.unitSet = unitSet;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are
// not set
if (!(object instanceof Virtue)) {
return false;
}
Virtue other = (Virtue) object;
if ((this.id == null && other.id != null)
|| (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.game.database.entity.Virtue[id=" + id + "]";
}
}

You have a problem with the identity of the Unit objects. You're using in your code a HashSet which relies on equals and hashCode methods which are overridden in your code.
If you run the main method in the code below, you will see that after adding the Unit objects there is only one of them in the set (I reused your original code but I simplified it a bit):
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
public class Unit {
private Integer id;
private Integer unitId;
private String name;
private Date registrationDate;
private String service;
private String nation;
public Unit() {
}
public Unit(Integer id) {
this.id = id;
}
public Unit(Integer unitId, String name, Date registrationDate, String service, String nation) {
this.unitId = unitId;
this.name = name;
this.registrationDate = registrationDate;
this.service = service;
this.nation = nation;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getUnitId() {
return unitId;
}
public void setUnitId(Integer unitId) {
this.unitId = unitId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getRegistrationDate() {
return registrationDate;
}
public void setRegistrationDate(Date registrationDate) {
this.registrationDate = registrationDate;
}
public String getService() {
return service;
}
public void setService(String service) {
this.service = service;
}
public String getNation() {
return nation;
}
public void setNation(String nation) {
this.nation = nation;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Unit)) {
return false;
}
Unit other = (Unit) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.game.database.entity.Unit[id=" + id + "]";
}
public static void main(String... args) {
Unit unit1 = new Unit(1, "Test Unit1", new Date(), "DisService", "MyNation");
Unit unit2 = new Unit(2, "Test Unit2", new Date(), "DisService", "TheirNation");
Unit unit3 = new Unit(3, "Test Unit3", new Date(), "DisService", "TheirNation");
Set unitSet = new HashSet();
unitSet.add(unit2);
unitSet.add(unit1);
unitSet.add(unit3);
System.out.println(unitSet.size());
}
If you comment out the equals() and hashCode() and run the code again you will see three objects in the set.
Your equals() method is based on the id property which is set by hibernate at time the object is being persisted and not at the time of adding to the set. It means that the Unit has always a null id and hashCode = 0 when added to the set. I recommend reading this article: http://community.jboss.org/wiki/EqualsandHashCode
Hope it helps!

Related

Java Persistence: Cannot add or update a child row: a foreign key constraint fails

Basically I'm implementing a PDS (Personal Data Sheet) so I have tables such as Client (employee), Personalinfo, Otherinfo.
Client table structure:
idClients, name, institute, username, password, usertype
Personalinfo table structure:
idPersonalInfo, agencyno, bloodtype, status, citizenship, address, idClients
I can add client successfully but when I'm trying to add/update personalinfo, I get
MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails
In personalinfo class I have this line also:
#JoinColumn(name = "idClients", referencedColumnName = "idClients", insertable = false, updatable = false)
In Clients class I also included:
#OneToOne(cascade = CascadeType.ALL, mappedBy = "clients")
private Personalinfo personalinfo;
But I can't figure out why I'm getting constraint violations.
Error Code: 1452
Call: INSERT INTO personalinfo (...) VALUES (...)
bind => [7parameters bound]
Query: InsertObjectQuery(com.profiling.database.Personalinfo[ idPersonalInfo=null ])
EDIT:
if (personal != null) {
.....
personal.setClients(client);
personal.setIdPersonalInfo(client.getIdClients());
EntityManager em = emanager.getEntityManager();
em.getTransaction().begin();
em.persist(personal);
em.getTransaction().commit();
JOptionPane.showMessageDialog(rootPane, "Personal Info Updated Successfully");
} else {
personal = new Personalinfo();
....
personal.setClients(client);
client.setPersonalinfo(personal);
EntityManager em = emanager.getEntityManager();
em.getTransaction().begin();
em.persist(personal);
em.getTransaction().commit();
JOptionPane.showMessageDialog(rootPane, "New Personal Info Save");
}
EDIT
Client Class:
#Entity
#Table(name = "clients")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Clients.findAll", query = "SELECT c FROM Clients c"),
#NamedQuery(name = "Clients.findByIdClients", query = "SELECT c FROM Clients c WHERE c.idClients = :idClients"),
#NamedQuery(name = "Clients.findByFirstName", query = "SELECT c FROM Clients c WHERE c.firstName = :firstName"),
#NamedQuery(name = "Clients.findByGender", query = "SELECT c FROM Clients c WHERE c.gender = :gender"),
#NamedQuery(name = "Clients.findByLastName", query = "SELECT c FROM Clients c WHERE c.lastName = :lastName"),
#NamedQuery(name = "Clients.findByMiddlename", query = "SELECT c FROM Clients c WHERE c.middlename = :middlename"),
#NamedQuery(name = "Clients.findByNameExtension", query = "SELECT c FROM Clients c WHERE c.nameExtension = :nameExtension")})
public class Clients implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "idClients")
private Integer idClients;
#Column(name = "FirstName")
private String firstName;
#Column(name = "Gender")
private String gender;
#Column(name = "LastName")
private String lastName;
#Column(name = "Middlename")
private String middlename;
#Column(name = "NameExtension")
private String nameExtension;
#Column(name = "Institute")
private String institute;
//value added
#Column(name = "username")
private String username;
#Column(name = "password")
private String password;
#Column(name = "userType")
private String userType;
#OneToMany(mappedBy = "idClients")
private List<Workexpe> workexpeList;
#OneToMany(mappedBy = "idClients")
private List<Ratingscore> ratingscoreList;
#OneToOne(cascade = CascadeType.ALL, mappedBy = "clients")
private Familyback familyback;
#OneToMany(mappedBy = "idClients")
private List<Civilservice> civilserviceList;
#OneToMany(mappedBy = "idClients")
private List<Staffscore> staffscoreList;
#OneToMany(mappedBy = "idClients")
private List<Referenceinfo> referenceinfoList;
#OneToOne(cascade = CascadeType.ALL, mappedBy = "clients")
private Personalinfo personalinfo;
#OneToOne(cascade = CascadeType.ALL, mappedBy = "clients")
// #OneToOne(mappedBy = "idClients")
private Otherinfo otherinfo;
#OneToMany(mappedBy = "idClients")
private List<Trainingprog> trainingprogList;
#OneToMany(mappedBy = "idClients")
private List<Children> childrenList;
#OneToMany(mappedBy = "idClients")
private List<Specialskills> specialskillsList;
#OneToMany(mappedBy = "idClients")
private List<Educback> educbackList;
#OneToMany(mappedBy = "idClients")
private List<Voluntarywork> voluntaryworkList;
public Clients() {
}
public Clients(Integer idClients) {
this.idClients = idClients;
}
public Integer getIdClients() {
return idClients;
}
public void setIdClients(Integer idClients) {
this.idClients = idClients;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getMiddlename() {
return middlename;
}
public void setMiddlename(String middlename) {
this.middlename = middlename;
}
public String getNameExtension() {
return nameExtension;
}
public void setNameExtension(String nameExtension) {
this.nameExtension = nameExtension;
}
#XmlTransient
public List<Workexpe> getWorkexpeList() {
return workexpeList;
}
public void setWorkexpeList(List<Workexpe> workexpeList) {
this.workexpeList = workexpeList;
}
#XmlTransient
public List<Ratingscore> getRatingscoreList() {
return ratingscoreList;
}
public void setRatingscoreList(List<Ratingscore> ratingscoreList) {
this.ratingscoreList = ratingscoreList;
}
public Familyback getFamilyback() {
return familyback;
}
public void setFamilyback(Familyback familyback) {
this.familyback = familyback;
}
#XmlTransient
public List<Civilservice> getCivilserviceList() {
return civilserviceList;
}
public void setCivilserviceList(List<Civilservice> civilserviceList) {
this.civilserviceList = civilserviceList;
}
#XmlTransient
public List<Staffscore> getStaffscoreList() {
return staffscoreList;
}
public void setStaffscoreList(List<Staffscore> staffscoreList) {
this.staffscoreList = staffscoreList;
}
#XmlTransient
public List<Referenceinfo> getReferenceinfoList() {
return referenceinfoList;
}
public void setReferenceinfoList(List<Referenceinfo> referenceinfoList) {
this.referenceinfoList = referenceinfoList;
}
public Personalinfo getPersonalinfo() {
return personalinfo;
}
public void setPersonalinfo(Personalinfo personalinfo) {
this.personalinfo = personalinfo;
}
public Otherinfo getOtherinfo() {
return otherinfo;
}
public void setOtherinfo(Otherinfo otherinfo) {
this.otherinfo = otherinfo;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUserType() {
return userType;
}
public void setUserType(String userType) {
this.userType = userType;
}
#XmlTransient
public List<Trainingprog> getTrainingprogList() {
return trainingprogList;
}
public void setTrainingprogList(List<Trainingprog> trainingprogList) {
this.trainingprogList = trainingprogList;
}
#XmlTransient
public List<Children> getChildrenList() {
return childrenList;
}
public void setChildrenList(List<Children> childrenList) {
this.childrenList = childrenList;
}
#XmlTransient
public List<Specialskills> getSpecialskillsList() {
return specialskillsList;
}
public void setSpecialskillsList(List<Specialskills> specialskillsList) {
this.specialskillsList = specialskillsList;
}
#XmlTransient
public List<Educback> getEducbackList() {
return educbackList;
}
public void setEducbackList(List<Educback> educbackList) {
this.educbackList = educbackList;
}
#XmlTransient
public List<Voluntarywork> getVoluntaryworkList() {
return voluntaryworkList;
}
public void setVoluntaryworkList(List<Voluntarywork> voluntaryworkList) {
this.voluntaryworkList = voluntaryworkList;
}
#Override
public int hashCode() {
int hash = 0;
hash += (idClients != null ? idClients.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Clients)) {
return false;
}
Clients other = (Clients) object;
if ((this.idClients == null && other.idClients != null) || (this.idClients != null && !this.idClients.equals(other.idClients))) {
return false;
}
return true;
}
#Override
public String toString() {
return this.lastName + ", " + this.firstName;
}
public String getInstitute() {
return institute;
}
public void setInstitute(String institute) {
this.institute = institute;
}
}
Personalinfo
#Entity
#Table(name = "personalinfo")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Personalinfo.findAll", query = "SELECT p FROM Personalinfo p"),
#NamedQuery(name = "Personalinfo.findByIdPersonalInfo", query = "SELECT p FROM Personalinfo p WHERE p.idPersonalInfo = :idPersonalInfo"),
#NamedQuery(name = "Personalinfo.findByAgencyNumber", query = "SELECT p FROM Personalinfo p WHERE p.agencyNumber = :agencyNumber"),
#NamedQuery(name = "Personalinfo.findByBloodType", query = "SELECT p FROM Personalinfo p WHERE p.bloodType = :bloodType"),
#NamedQuery(name = "Personalinfo.findByCellphone", query = "SELECT p FROM Personalinfo p WHERE p.cellphone = :cellphone"),
#NamedQuery(name = "Personalinfo.findByCevilStatus", query = "SELECT p FROM Personalinfo p WHERE p.cevilStatus = :cevilStatus"),
#NamedQuery(name = "Personalinfo.findByCitizenship", query = "SELECT p FROM Personalinfo p WHERE p.citizenship = :citizenship"),
#NamedQuery(name = "Personalinfo.findByDateofBirth", query = "SELECT p FROM Personalinfo p WHERE p.dateofBirth = :dateofBirth"),
#NamedQuery(name = "Personalinfo.findByEmailAdd", query = "SELECT p FROM Personalinfo p WHERE p.emailAdd = :emailAdd"),
#NamedQuery(name = "Personalinfo.findByGsis", query = "SELECT p FROM Personalinfo p WHERE p.gsis = :gsis"),
#NamedQuery(name = "Personalinfo.findByHeight", query = "SELECT p FROM Personalinfo p WHERE p.height = :height"),
#NamedQuery(name = "Personalinfo.findByPagibig", query = "SELECT p FROM Personalinfo p WHERE p.pagibig = :pagibig"),
#NamedQuery(name = "Personalinfo.findByPermanentAddress", query = "SELECT p FROM Personalinfo p WHERE p.permanentAddress = :permanentAddress"),
#NamedQuery(name = "Personalinfo.findByPhilHealth", query = "SELECT p FROM Personalinfo p WHERE p.philHealth = :philHealth"),
#NamedQuery(name = "Personalinfo.findByPlaceofBirth", query = "SELECT p FROM Personalinfo p WHERE p.placeofBirth = :placeofBirth"),
#NamedQuery(name = "Personalinfo.findByResidentialAddress", query = "SELECT p FROM Personalinfo p WHERE p.residentialAddress = :residentialAddress"),
#NamedQuery(name = "Personalinfo.findBySssNo", query = "SELECT p FROM Personalinfo p WHERE p.sssNo = :sssNo"),
#NamedQuery(name = "Personalinfo.findByTelephone1", query = "SELECT p FROM Personalinfo p WHERE p.telephone1 = :telephone1"),
#NamedQuery(name = "Personalinfo.findByTelephone2", query = "SELECT p FROM Personalinfo p WHERE p.telephone2 = :telephone2"),
#NamedQuery(name = "Personalinfo.findByTin", query = "SELECT p FROM Personalinfo p WHERE p.tin = :tin"),
#NamedQuery(name = "Personalinfo.findByWeight", query = "SELECT p FROM Personalinfo p WHERE p.weight = :weight"),
#NamedQuery(name = "Personalinfo.findByZipcode1", query = "SELECT p FROM Personalinfo p WHERE p.zipcode1 = :zipcode1"),
#NamedQuery(name = "Personalinfo.findByZipcode2", query = "SELECT p FROM Personalinfo p WHERE p.zipcode2 = :zipcode2")})
public class Personalinfo implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "idPersonalInfo")
private Integer idPersonalInfo;
#Column(name = "AgencyNumber")
private String agencyNumber;
#Column(name = "BloodType")
private String bloodType;
#Column(name = "Cellphone")
private String cellphone;
#Column(name = "CevilStatus")
private String cevilStatus;
#Column(name = "Citizenship")
private String citizenship;
#Column(name = "DateofBirth")
#Temporal(TemporalType.TIMESTAMP)
private Date dateofBirth;
#Column(name = "EmailAdd")
private String emailAdd;
#Column(name = "GSIS")
private String gsis;
#Column(name = "Height")
private String height;
#Column(name = "Pagibig")
private String pagibig;
#Column(name = "PermanentAddress")
private String permanentAddress;
#Column(name = "PhilHealth")
private String philHealth;
#Lob
#Column(name = "Picture")
private byte[] picture;
#Column(name = "PlaceofBirth")
private String placeofBirth;
#Column(name = "ResidentialAddress")
private String residentialAddress;
#Column(name = "SssNo")
private String sssNo;
#Column(name = "Telephone1")
private String telephone1;
#Column(name = "Telephone2")
private String telephone2;
#Column(name = "Tin")
private String tin;
#Column(name = "Weight")
private String weight;
#Column(name = "Zipcode1")
private String zipcode1;
#Column(name = "Zipcode2")
private String zipcode2;
#Column(name = "IdClients")
private String idClients;
#JoinColumn(name = "idClients", referencedColumnName = "idClients", insertable = false, updatable = false)
// #JoinColumn(name = "idClients", referencedColumnName = "idClients")
#OneToOne(optional = false)
private Clients clients;
public Personalinfo() {
}
public Personalinfo(Integer idPersonalInfo) {
this.idPersonalInfo = idPersonalInfo;
}
public Integer getIdPersonalInfo() {
return idPersonalInfo;
}
public void setIdPersonalInfo(Integer idPersonalInfo) {
this.idPersonalInfo = idPersonalInfo;
}
public String getAgencyNumber() {
return agencyNumber;
}
public void setAgencyNumber(String agencyNumber) {
this.agencyNumber = agencyNumber;
}
public String getBloodType() {
return bloodType;
}
public void setBloodType(String bloodType) {
this.bloodType = bloodType;
}
public String getCellphone() {
return cellphone;
}
public void setCellphone(String cellphone) {
this.cellphone = cellphone;
}
public String getCevilStatus() {
return cevilStatus;
}
public void setCevilStatus(String cevilStatus) {
this.cevilStatus = cevilStatus;
}
public String getCitizenship() {
return citizenship;
}
public void setCitizenship(String citizenship) {
this.citizenship = citizenship;
}
public Date getDateofBirth() {
return dateofBirth;
}
public void setDateofBirth(Date dateofBirth) {
this.dateofBirth = dateofBirth;
}
public String getEmailAdd() {
return emailAdd;
}
public void setEmailAdd(String emailAdd) {
this.emailAdd = emailAdd;
}
public String getGsis() {
return gsis;
}
public void setGsis(String gsis) {
this.gsis = gsis;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
public String getPagibig() {
return pagibig;
}
public void setPagibig(String pagibig) {
this.pagibig = pagibig;
}
public String getPermanentAddress() {
return permanentAddress;
}
public void setPermanentAddress(String permanentAddress) {
this.permanentAddress = permanentAddress;
}
public String getPhilHealth() {
return philHealth;
}
public void setPhilHealth(String philHealth) {
this.philHealth = philHealth;
}
public byte[] getPicture() {
return picture;
}
public void setPicture(byte[] picture) {
this.picture = picture;
}
public String getPlaceofBirth() {
return placeofBirth;
}
public void setPlaceofBirth(String placeofBirth) {
this.placeofBirth = placeofBirth;
}
public String getResidentialAddress() {
return residentialAddress;
}
public void setResidentialAddress(String residentialAddress) {
this.residentialAddress = residentialAddress;
}
public String getSssNo() {
return sssNo;
}
public void setSssNo(String sssNo) {
this.sssNo = sssNo;
}
public String getTelephone1() {
return telephone1;
}
public void setTelephone1(String telephone1) {
this.telephone1 = telephone1;
}
public String getTelephone2() {
return telephone2;
}
public void setTelephone2(String telephone2) {
this.telephone2 = telephone2;
}
public String getTin() {
return tin;
}
public void setTin(String tin) {
this.tin = tin;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public String getZipcode1() {
return zipcode1;
}
public void setZipcode1(String zipcode1) {
this.zipcode1 = zipcode1;
}
public String getZipcode2() {
return zipcode2;
}
public void setZipcode2(String zipcode2) {
this.zipcode2 = zipcode2;
}
#MapsId
public Clients getClients() {
return clients;
}
#MapsId
public void setClients(Clients clients) {
this.clients = clients;
}
public String getIdClient() {
return idClients;
}
public void setIdClients(String clients) {
this.idClients = clients;
}
#Override
public int hashCode() {
int hash = 0;
hash += (idPersonalInfo != null ? idPersonalInfo.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Personalinfo)) {
return false;
}
Personalinfo other = (Personalinfo) object;
if ((this.idPersonalInfo == null && other.idPersonalInfo != null) || (this.idPersonalInfo != null && !this.idPersonalInfo.equals(other.idPersonalInfo))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.doscst.profiling.database.Personalinfo[ idPersonalInfo=" + idPersonalInfo + " ]";
}
}
Suppose you try with this in PersonalInfo class and check.
#OneToOne
#JoinColumn(name = "idClients")
private Clients clients;

Use join and subquery with criteria in hibernate

I searched lot. But can't find solution for my case. i want create hibernate criteria for following query.
SELECT * FROM patient as p1 LEFT OUTER JOIN (SELECT * FROM patient_caller_admin_map WHERE caller_admin_id='1') as pca ON p1.patient_id=pca.patient_id;
i went through the DetachedCriteria , Criteria and created the following things. But don't know how to use LEFT_JOIN by joining both.
DetachedCriteria inner=DetachedCriteria.forClass(PatientCallerAdminMap.class, "patientCallerAdmin");
Criteria cr1=this.sessionFactory.getCurrentSession().createCriteria(Patient.class,"patient");
PatientCallerAdminMap Entity:
/**
* PatientCallerAdminMap generated by hbm2java
*/
#Entity
#Table(name = "patient_caller_admin_map", catalog = "test")
public class PatientCallerAdminMap implements java.io.Serializable {
private PatientCallerAdminMapId id;
private CallerAdmin callerAdmin;
private Caller caller;
private Patient patient;
private String notes;
private Integer isArchived;
private Integer patientStatus;
private Set<CallLog> callLogs = new HashSet<CallLog>(0);
private Set<CallLog> callLogs_1 = new HashSet<CallLog>(0);
public PatientCallerAdminMap() {
}
public PatientCallerAdminMap(PatientCallerAdminMapId id,
CallerAdmin callerAdmin, Patient patient) {
this.id = id;
this.callerAdmin = callerAdmin;
this.patient = patient;
}
public PatientCallerAdminMap(PatientCallerAdminMapId id,
CallerAdmin callerAdmin, Caller caller, Patient patient,
String notes, Integer isArchived, Integer patientStatus,
Set<CallLog> callLogs, Set<CallLog> callLogs_1) {
this.id = id;
this.callerAdmin = callerAdmin;
this.caller = caller;
this.patient = patient;
this.notes = notes;
this.isArchived = isArchived;
this.patientStatus = patientStatus;
this.callLogs = callLogs;
this.callLogs_1 = callLogs_1;
}
#EmbeddedId
#AttributeOverrides({
#AttributeOverride(name = "patientId", column = #Column(name = "patient_id", nullable = false)),
#AttributeOverride(name = "callerAdminId", column = #Column(name = "caller_admin_id", nullable = false)) })
public PatientCallerAdminMapId getId() {
return this.id;
}
public void setId(PatientCallerAdminMapId id) {
this.id = id;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "caller_admin_id", nullable = false, insertable = false, updatable = false)
public CallerAdmin getCallerAdmin() {
return this.callerAdmin;
}
public void setCallerAdmin(CallerAdmin callerAdmin) {
this.callerAdmin = callerAdmin;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "caller_id")
public Caller getCaller() {
return this.caller;
}
public void setCaller(Caller caller) {
this.caller = caller;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "patient_id", nullable = false, insertable = false, updatable = false)
public Patient getPatient() {
return this.patient;
}
public void setPatient(Patient patient) {
this.patient = patient;
}
#Column(name = "notes", length = 600)
public String getNotes() {
return this.notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
#Column(name = "is_archived")
public Integer getIsArchived() {
return this.isArchived;
}
public void setIsArchived(Integer isArchived) {
this.isArchived = isArchived;
}
#Column(name = "patient_status")
public Integer getPatientStatus() {
return this.patientStatus;
}
public void setPatientStatus(Integer patientStatus) {
this.patientStatus = patientStatus;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "patientCallerAdminMap")
public Set<CallLog> getCallLogs() {
return this.callLogs;
}
public void setCallLogs(Set<CallLog> callLogs) {
this.callLogs = callLogs;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "patientCallerAdminMap")
public Set<CallLog> getCallLogs_1() {
return this.callLogs_1;
}
public void setCallLogs_1(Set<CallLog> callLogs_1) {
this.callLogs_1 = callLogs_1;
}
}
Patient Entity Class:
#Entity
#Table(name = "patient", catalog = "test")
public class Patient implements java.io.Serializable {
private String patientId;
private String addedDate;
private String name;
private String dateOfBirth;
private String gender;
private String address;
private String phoneNumber;
private Integer tier;
private Integer patientStatus;
private Integer status;
private Set<PatientCallerAdminMap> patientCallerAdminMaps = new HashSet<PatientCallerAdminMap>(
0);
public Patient() {
}
public Patient(String patientId) {
this.patientId = patientId;
}
public Patient(String patientId,String addedDate, String timeOfCrash,
String name, String dateOfBirth, String gender,
String address,
String phoneNumber,Integer tier, Integer patientStatus,
Integer status,
Set<PatientCallerAdminMap> patientCallerAdminMaps,
) {
this.patientId = patientId;
this.addedDate = addedDate;
this.name = name;
this.dateOfBirth = dateOfBirth;
this.gender = gender;
this.address = address;
this.phoneNumber = phoneNumber;
this.tier=tier;
this.patientStatus = patientStatus;
this.status = status;
this.patientCallerAdminMaps = patientCallerAdminMaps;
}
#Id
#Column(name = "patient_id", unique = true, nullable = false)
public String getPatientId() {
return this.patientId;
}
public void setPatientId(String patientId) {
this.patientId = patientId;
}
#Column(name = "added_date", length = 45)
public String getAddedDate() {
return addedDate;
}
public void setAddedDate(String addedDate) {
this.addedDate = addedDate;
}
#Column(name = "name", length = 100)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
#Column(name = "date_of_birth", length = 45)
public String getDateOfBirth() {
return this.dateOfBirth;
}
public void setDateOfBirth(String dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
#Column(name = "gender", length = 5)
public String getGender() {
return this.gender;
}
public void setGender(String gender) {
this.gender = gender;
}
#Column(name = "address", length = 200)
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
#Column(name = "phone_number", length = 20)
public String getPhoneNumber() {
return this.phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
#Column(name = "tier")
public Integer getTier() {
return this.tier;
}
public void setTier(Integer tier) {
this.tier = tier;
}
#Column(name = "patient_status")
public Integer getPatientStatus() {
return this.patientStatus;
}
public void setPatientStatus(Integer patientStatus) {
this.patientStatus = patientStatus;
}
#Column(name = "status")
public Integer getStatus() {
return this.status;
}
public void setStatus(Integer status) {
this.status = status;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "patient")
public Set<PatientCallerAdminMap> getPatientCallerAdminMaps() {
return this.patientCallerAdminMaps;
}
public void setPatientCallerAdminMaps(
Set<PatientCallerAdminMap> patientCallerAdminMaps) {
this.patientCallerAdminMaps = patientCallerAdminMaps;
}
}
Please help to solve this.
Maybe you can achieve this without using subquery so the query become simpler :
Criteria cr1=this.sessionFactory.getCurrentSession().createCriteria(Patient.class,"patient");
cr2=cr1.createCriteria("patientCallerAdminMaps ",CriteriaSpecification.LEFT_JOIN);
cr3= cr2.createCriteria("callerAdmin",CriteriaSpecification.LEFT_JOIN);
cr3.add(Restrictions.eq("id", "1"));
For the "select *" you can't do it with criteria. This criteria will return a list of Patient entity.
If really want * you will have to add alias on subcriteria and use Projection to select explicitly the fields that you want

JPA - Getting data through a foreign key

I'm new to JPA, I used JDBC and now trying to switch it over to JPA usage. I've got these two classes
#Entity
#Table(name = "work_entry")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "WorkEntry.findAll", query = "SELECT w FROM WorkEntry w"),
#NamedQuery(name = "WorkEntry.findByWorkEntryId", query = "SELECT w FROM WorkEntry w WHERE w.workEntryId = :workEntryId"),
#NamedQuery(name = "WorkEntry.findByDate", query = "SELECT w FROM WorkEntry w WHERE w.date = :date"),
#NamedQuery(name = "WorkEntry.findByHoursWorked", query = "SELECT w FROM WorkEntry w WHERE w.hoursWorked = :hoursWorked")})
public class WorkEntry implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "work_entry_id")
private Integer workEntryId;
#Column(name = "date")
#Temporal(TemporalType.DATE)
private Date date;
// #Max(value=?) #Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
#Column(name = "hours_worked")
private Double hoursWorked;
#JoinColumn(name = "activity_id", referencedColumnName = "activity_id")
#ManyToOne
private Activity activityId;
#JoinColumn(name = "customer_id", referencedColumnName = "customer_id")
#ManyToOne
private Customer customerId;
public WorkEntry() {
}
public WorkEntry(Date date, Double hoursWorked, Customer customerId, Activity activityId) {
this.date = date;
this.hoursWorked = hoursWorked;
this.activityId = activityId;
this.customerId = customerId;
}
public WorkEntry(Integer workEntryId) {
this.workEntryId = workEntryId;
}
public Integer getWorkEntryId() {
return workEntryId;
}
public void setWorkEntryId(Integer workEntryId) {
this.workEntryId = workEntryId;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Double getHoursWorked() {
return hoursWorked;
}
public void setHoursWorked(Double hoursWorked) {
this.hoursWorked = hoursWorked;
}
public Activity getActivityId() {
return activityId;
}
public void setActivityId(Activity activityId) {
this.activityId = activityId;
}
public Customer getCustomerId() {
return customerId;
}
public void setCustomerId(Customer customerId) {
this.customerId = customerId;
}
#Override
public int hashCode() {
int hash = 0;
hash += (workEntryId != null ? workEntryId.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof WorkEntry)) {
return false;
}
WorkEntry other = (WorkEntry) object;
if ((this.workEntryId == null && other.workEntryId != null) || (this.workEntryId != null && !this.workEntryId.equals(other.workEntryId))) {
return false;
}
return true;
}
#Override
public String toString() {
return "consultant.billing.entity.WorkEntry[ workEntryId=" + workEntryId + " ]";
}
And
#Entity
#Table(name = "customer")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Customer.findAll", query = "SELECT c FROM Customer c"),
#NamedQuery(name = "Customer.findByCustomerId", query = "SELECT c FROM Customer c WHERE c.customerId = :customerId"),
#NamedQuery(name = "Customer.findByFirstName", query = "SELECT c FROM Customer c WHERE c.firstName = :firstName"),
#NamedQuery(name = "Customer.findByLastName", query = "SELECT c FROM Customer c WHERE c.lastName = :lastName"),
#NamedQuery(name = "Customer.findByStreetAddress", query = "SELECT c FROM Customer c WHERE c.streetAddress = :streetAddress"),
#NamedQuery(name = "Customer.findByCity", query = "SELECT c FROM Customer c WHERE c.city = :city"),
#NamedQuery(name = "Customer.findByState", query = "SELECT c FROM Customer c WHERE c.state = :state"),
#NamedQuery(name = "Customer.findByPostalCode", query = "SELECT c FROM Customer c WHERE c.postalCode = :postalCode"),
#NamedQuery(name = "Customer.findByPhoneNumber", query = "SELECT c FROM Customer c WHERE c.phoneNumber = :phoneNumber"),
#NamedQuery(name = "Customer.findByEmail", query = "SELECT c FROM Customer c WHERE c.email = :email")})
public class Customer implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "customer_id")
private Integer customerId;
#Size(max = 75)
#Column(name = "first_name")
private String firstName;
#Size(max = 75)
#Column(name = "last_name")
private String lastName;
#Size(max = 250)
#Column(name = "street_address")
private String streetAddress;
#Size(max = 50)
#Column(name = "city")
private String city;
#Size(max = 50)
#Column(name = "state")
private String state;
#Size(max = 45)
#Column(name = "postal_code")
private String postalCode;
#Size(max = 45)
#Column(name = "phone_number")
private String phoneNumber;
// #Pattern(regexp="[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", message="Invalid email")//if the field contains email address consider using this annotation to enforce field validation
#Size(max = 250)
#Column(name = "email")
private String email;
#OneToMany(mappedBy = "customerId")
private Collection<ExpenseEntry> expenseEntryCollection;
#OneToMany(mappedBy = "customerId")
private Collection<WorkEntry> workEntryCollection;
public Customer() {
}
public Customer(Integer customerId, String firstName, String lastName, String streetAddress, String city, String state, String postalCode, String phoneNumber, String email) {
this.customerId = customerId;
this.firstName = firstName;
this.lastName = lastName;
this.streetAddress = streetAddress;
this.city = city;
this.state = state;
this.postalCode = postalCode;
this.phoneNumber = phoneNumber;
this.email = email;
}
public Customer(String firstName, String lastName, String streetAddress, String city, String state, String postalCode, String phoneNumber, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.streetAddress = streetAddress;
this.city = city;
this.state = state;
this.postalCode = postalCode;
this.phoneNumber = phoneNumber;
this.email = email;
}
public Customer(Integer customerId) {
this.customerId = customerId;
}
public Integer getCustomerId() {
return customerId;
}
public void setCustomerId(Integer customerId) {
this.customerId = customerId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getStreetAddress() {
return streetAddress;
}
public void setStreetAddress(String streetAddress) {
this.streetAddress = streetAddress;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#XmlTransient
public Collection<ExpenseEntry> getExpenseEntryCollection() {
return expenseEntryCollection;
}
public void setExpenseEntryCollection(Collection<ExpenseEntry> expenseEntryCollection) {
this.expenseEntryCollection = expenseEntryCollection;
}
#XmlTransient
public Collection<WorkEntry> getWorkEntryCollection() {
return workEntryCollection;
}
public void setWorkEntryCollection(Collection<WorkEntry> workEntryCollection) {
this.workEntryCollection = workEntryCollection;
}
#Override
public int hashCode() {
int hash = 0;
hash += (customerId != null ? customerId.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Customer)) {
return false;
}
Customer other = (Customer) object;
if ((this.customerId == null && other.customerId != null) || (this.customerId != null && !this.customerId.equals(other.customerId))) {
return false;
}
return true;
}
#Override
public String toString() {
return "consultant.billing.entity.Customer[ customerId=" + customerId + " ]";
}
Now, what I've done before is used a joined to get the WorkEntry based off the customerId. I know JPA is more object oriented and I want to know what would be the best way to go about getting all WorkEntries for a customerId and adding WorkEntries based off a customerId.
Thank you.
It would make more sense if you changed your definition to the folowing
#JoinColumn(name = "customer_id", referencedColumnName = "customer_id")
#ManyToOne
private Customer customer;
And change the corresponding getter and setter methods as well.
Then if you get a WorkEntry you can just get work entry.getCustomer ()
You and so need to be a bit more specific about the type in your Collection on Customer like List to give the provider some hints about how to implement the collection.
Once you have done that you should just be able to read the customer from the database and call customer.getWorkEntryCollection()

to get only parent object data in JPA

I am using java (Netbeans IDE) to create restful services. I have created two entity claees from two related tables. and i have also created the restful services from patterns. when I test the HTTP GET method for child table (in this case Category)it gives the data from child table as well as parent table but i need data from child table only with column value of the foreing key. Steps followed so far as follows :
I am created following two tables in mysql
1) site table
create table `revise`.site
(
siteId INT not null auto_increment primary key,
shortName VARCHAR(255),
longName VARCHAR(1024) ,
addressLineFirst VARCHAR(2024)l,
city VARCHAR(255) ,
state VARCHAR(255),
pincode VARCHAR(255),
country VARCHAR(255) ,
phoneNo VARCHAR(255),
mobileNo VARCHAR(255),
fax VARCHAR(255),
emailId VARCHAR(255),
logoSmall VARCHAR(1024),
logoBig VARCHAR(1024),
activeStatus VARCHAR(255),
action VARCHAR(255)
)
2) Category table
create table `revise`.category
(
categoryId INT not null auto_increment primary key,
siteId INT,
shortName VARCHAR(255),
longName VARCHAR(1024),
description VARCHAR(8000),
logoSmall VARCHAR(8000),
logoBig VARCHAR(8000),
CONSTRAINT fk_Site FOREIGN KEY (siteId) REFERENCES site(siteId) on delete cascade on update cascade
)
And from this two table i have created the following two entity classes
1) Site.java
#Entity
#Table(name = "site")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Site.findAll", query = "SELECT s FROM Site s"),
#NamedQuery(name = "Site.findBySiteId", query = "SELECT s FROM Site s WHERE s.siteId = :siteId"),
#NamedQuery(name = "Site.findByShortName", query = "SELECT s FROM Site s WHERE s.shortName = :shortName"),
#NamedQuery(name = "Site.findByLongName", query = "SELECT s FROM Site s WHERE s.longName = :longName"),
#NamedQuery(name = "Site.findByAddressLineFirst", query = "SELECT s FROM Site s WHERE s.addressLineFirst = :addressLineFirst"),
#NamedQuery(name = "Site.findByCity", query = "SELECT s FROM Site s WHERE s.city = :city"),
#NamedQuery(name = "Site.findByState", query = "SELECT s FROM Site s WHERE s.state = :state"),
#NamedQuery(name = "Site.findByPincode", query = "SELECT s FROM Site s WHERE s.pincode = :pincode"),
#NamedQuery(name = "Site.findByCountry", query = "SELECT s FROM Site s WHERE s.country = :country"),
#NamedQuery(name = "Site.findByPhoneNo", query = "SELECT s FROM Site s WHERE s.phoneNo = :phoneNo"),
#NamedQuery(name = "Site.findByMobileNo", query = "SELECT s FROM Site s WHERE s.mobileNo = :mobileNo"),
#NamedQuery(name = "Site.findByFax", query = "SELECT s FROM Site s WHERE s.fax = :fax"),
#NamedQuery(name = "Site.findByEmailId", query = "SELECT s FROM Site s WHERE s.emailId = :emailId"),
#NamedQuery(name = "Site.findByLogoSmall", query = "SELECT s FROM Site s WHERE s.logoSmall = :logoSmall"),
#NamedQuery(name = "Site.findByLogoBig", query = "SELECT s FROM Site s WHERE s.logoBig = :logoBig"),
#NamedQuery(name = "Site.findByActiveStatus", query = "SELECT s FROM Site s WHERE s.activeStatus = :activeStatus"),
#NamedQuery(name = "Site.findByAction", query = "SELECT s FROM Site s WHERE s.action = :action")})
public class Site implements Serializable {
#OneToMany(mappedBy = "siteId", fetch = FetchType.EAGER)
private List<Category> categoryList;
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "siteId")
private Integer siteId;
#Size(max = 255)
#Column(name = "shortName")
private String shortName;
#Size(max = 1024)
#Column(name = "longName")
private String longName;
#Size(max = 2024)
#Column(name = "addressLineFirst")
private String addressLineFirst;
#Size(max = 255)
#Column(name = "city")
private String city;
#Size(max = 255)
#Column(name = "state")
private String state;
#Size(max = 255)
#Column(name = "pincode")
private String pincode;
#Size(max = 255)
#Column(name = "country")
private String country;
#Size(max = 255)
#Column(name = "phoneNo")
private String phoneNo;
#Size(max = 255)
#Column(name = "mobileNo")
private String mobileNo;
// #Pattern(regexp="^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$", message="Invalid phone/fax format, should be as xxx-xxx-xxxx")//if the field contains phone or fax number consider using this annotation to enforce field validation
#Size(max = 255)
#Column(name = "fax")
private String fax;
#Size(max = 255)
#Column(name = "emailId")
private String emailId;
#Size(max = 1024)
#Column(name = "logoSmall")
private String logoSmall;
#Size(max = 1024)
#Column(name = "logoBig")
private String logoBig;
#Size(max = 255)
#Column(name = "activeStatus")
private String activeStatus;
#Size(max = 255)
#Column(name = "action")
private String action;
public Site() {
}
public Site(Integer siteId) {
this.siteId = siteId;
}
public Integer getSiteId() {
return siteId;
}
public void setSiteId(Integer siteId) {
this.siteId = siteId;
}
public String getShortName() {
return shortName;
}
public void setShortName(String shortName) {
this.shortName = shortName;
}
public String getLongName() {
return longName;
}
public void setLongName(String longName) {
this.longName = longName;
}
public String getAddressLineFirst() {
return addressLineFirst;
}
public void setAddressLineFirst(String addressLineFirst) {
this.addressLineFirst = addressLineFirst;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getPincode() {
return pincode;
}
public void setPincode(String pincode) {
this.pincode = pincode;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getPhoneNo() {
return phoneNo;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
public String getMobileNo() {
return mobileNo;
}
public void setMobileNo(String mobileNo) {
this.mobileNo = mobileNo;
}
public String getFax() {
return fax;
}
public void setFax(String fax) {
this.fax = fax;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public String getLogoSmall() {
return logoSmall;
}
public void setLogoSmall(String logoSmall) {
this.logoSmall = logoSmall;
}
public String getLogoBig() {
return logoBig;
}
public void setLogoBig(String logoBig) {
this.logoBig = logoBig;
}
public String getActiveStatus() {
return activeStatus;
}
public void setActiveStatus(String activeStatus) {
this.activeStatus = activeStatus;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
#Override
public int hashCode() {
int hash = 0;
hash += (siteId != null ? siteId.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Site)) {
return false;
}
Site other = (Site) object;
if ((this.siteId == null && other.siteId != null) || (this.siteId != null && !this.siteId.equals(other.siteId))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.ikanksha.reviseplus.api.entity.Site[ siteId=" + siteId + " ]";
}
}
2) Category.java
#Entity
#Table(name = "category")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Category.findAll", query = "SELECT c FROM Category c"),
#NamedQuery(name = "Category.findByCategoryId", query = "SELECT c FROM Category c WHERE c.categoryId = :categoryId"),
#NamedQuery(name = "Category.findByShortName", query = "SELECT c FROM Category c WHERE c.shortName = :shortName"),
#NamedQuery(name = "Category.findByLongName", query = "SELECT c FROM Category c WHERE c.longName = :longName"),
#NamedQuery(name = "Category.findByDescription", query = "SELECT c FROM Category c WHERE c.description = :description"),
#NamedQuery(name = "Category.findByLogoSmall", query = "SELECT c FROM Category c WHERE c.logoSmall = :logoSmall"),
#NamedQuery(name = "Category.findByLogoBig", query = "SELECT c FROM Category c WHERE c.logoBig = :logoBig")})
public class Category implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "categoryId")
private Integer categoryId;
#Size(max = 255)
#Column(name = "shortName")
private String shortName;
#Size(max = 1024)
#Column(name = "longName")
private String longName;
#Size(max = 8000)
#Column(name = "description")
private String description;
#Size(max = 8000)
#Column(name = "logoSmall")
private String logoSmall;
#Size(max = 8000)
#Column(name = "logoBig")
private String logoBig;
#OneToMany(mappedBy = "categoryId", fetch = FetchType.EAGER)
private List<Topic> topicList;
#JoinColumn(name = "siteId", referencedColumnName = "siteId")
#ManyToOne(fetch = FetchType.EAGER)
private Site siteId;
public Category() {
}
public Category(Integer categoryId) {
this.categoryId = categoryId;
}
public Integer getCategoryId() {
return categoryId;
}
public void setCategoryId(Integer categoryId) {
this.categoryId = categoryId;
}
public String getShortName() {
return shortName;
}
public void setShortName(String shortName) {
this.shortName = shortName;
}
public String getLongName() {
return longName;
}
public void setLongName(String longName) {
this.longName = longName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getLogoSmall() {
return logoSmall;
}
public void setLogoSmall(String logoSmall) {
this.logoSmall = logoSmall;
}
public String getLogoBig() {
return logoBig;
}
public void setLogoBig(String logoBig) {
this.logoBig = logoBig;
}
public Site getSiteId() {
return siteId;
}
public void setSiteId(Site siteId) {
this.siteId = siteId;
}
#Override
public int hashCode() {
int hash = 0;
hash += (categoryId != null ? categoryId.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Category)) {
return false;
}
Category other = (Category) object;
if ((this.categoryId == null && other.categoryId != null) || (this.categoryId != null && !this.categoryId.equals(other.categoryId))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.ikanksha.reviseplus.api.entity.Category[ categoryId=" + categoryId + " ]";
}
}
and I getting following json data as for the request
http://localhost:8080/ReviseAPIDemo-war/webresources/categories/1
{
"categoryId": "1",
"description": "fdgfd",
"logoBig": "dfgf",
"logoSmall": "fgdf",
"longName": "lnhdr",
"shortName": "shrt",
"siteId": {
"addressLineFirst": "Vijapurroad",
"city": "Solapur",
"country": "India",
"emailId": "soni#dhb.com",
"fax": "834343443",
"logoBig": "biglogo",
"logoSmall": "small",
"longName": "DHB Soni College",
"mobileNo": "9898123844",
"phoneNo": "23203361",
"pincode": "413004",
"shortName": "DHB",
"siteId": "1",
"state": "Maharashtra"
}
}
but i need response as
{
"categoryId": "1",
"description": "fdgfd",
"logoBig": "dfgf",
"logoSmall": "fgdf",
"longName": "lnhdr",
"shortName": "shrt",
"siteId": "1",
}
The thing you could do is load the Category entity (in your JAX-RS resource?) read the Id from the corresponding Site, then create a new Site object with all properties null, set the right siteId and then store it on the Category object. Then the JSON marshaller should only return the id.

get more query in generated restful web service

I create a Restful web service with netbeans, I just specify the database and netbeans to create everything. IN sub-resources , i have only 4 URI:
converter.city (http://localhost:8080/Data/resources/converter.city)
converter.city/{id}(http://localhost:8080/Data/resources/converter.city/{id})
converter.city/{from}/{to(http://localhost:8080/Data/resources/converter.city/{from}/{to})
converter.city/count(http://localhost:8080/Data/resources/converter.city/count)
this is the generated code , watch the first part
#Entity
#Table(name = "City")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "City.findAll", query = "SELECT c FROM City c"),
#NamedQuery(name = "City.findById", query = "SELECT c FROM City c WHERE c.id = :id"),
#NamedQuery(name = "City.findByName", query = "SELECT c FROM City c WHERE c.name = :name"),
#NamedQuery(name = "City.findByCountryCode", query = "SELECT c FROM City c WHERE c.countryCode = :countryCode"),
#NamedQuery(name = "City.findByDistrict", query = "SELECT c FROM City c WHERE c.district = :district"),
#NamedQuery(name = "City.findByPopulation", query = "SELECT c FROM City c WHERE c.population = :population")})
public class City implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#NotNull
#Column(name = "ID")
private Integer id;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 35)
#Column(name = "Name")
private String name;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 3)
#Column(name = "CountryCode")
private String countryCode;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 20)
#Column(name = "District")
private String district;
#Basic(optional = false)
#NotNull
#Column(name = "Population")
private int population;
public City() {
}
public City(Integer id) {
this.id = id;
}
public City(Integer id, String name, String countryCode, String district, int population) {
this.id = id;
this.name = name;
this.countryCode = countryCode;
this.district = district;
this.population = population;
}
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;
}
public String getCountryCode() {
return countryCode;
}
public void setCountryCode(String countryCode) {
this.countryCode = countryCode;
}
public String getDistrict() {
return district;
}
public void setDistrict(String district) {
this.district = district;
}
public int getPopulation() {
return population;
}
public void setPopulation(int population) {
this.population = population;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof City)) {
return false;
}
City other = (City) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "converter.City[ id=" + id + " ]";
}
In the generated code there are many query and among them one that interests me
#NamedQuery(name = "City.findByCountryCode", query = "SELECT c FROM City c WHERE c.countryCode = :countryCode")
How can i use City.findByCountryCode ?
Query query = em.createNamedQuery("City.findByCountryCode")
.setParameter("countryCode", yourCountryCode);

Categories