Rest API order by name - rest

I'm trying to create my own REST API and I'm having trouble trying to order my data by name. currently, I am able to display all the data from the styles table, however, I wish to sort them alphabetically.
I was able to do a filter by extracting the year from the date and checking if that was in the database, this is shown in
public List<Beers> getAllBeersByYear(int year) {
EntityManager em = DBUtil.getEMF().createEntityManager();
List<Beers> list = null;
List<Beers> beersToRemove = new ArrayList<>();
try {
list = em.createNamedQuery("Beers.findAll", Beers.class)
.getResultList();
if (list == null || list.isEmpty()) {
list = null;
}
} finally {
em.close();
}
Calendar cal = Calendar.getInstance();
for (Beers beer : list) {
cal.setTime(beer.getLastMod());
if (cal.get(Calendar.YEAR) != year) {
beersToRemove.add(beer);
}
}
list.removeAll(beersToRemove);
return list;
}
the controller is
#GetMapping(produces=MediaType.APPLICATION_JSON_VALUE)
public List<Styles> GetAllStyles() {
return service.getAllStyles();
}
would it be possible to do something similar to the service and controller where instead of filtering the data, it can sort by the name of a column
the service is
public List<Styles> getAllStyles() {
EntityManager em = DBUtil.getEMF().createEntityManager();
List<Styles> list = null;
try {
list = em.createNamedQuery("Styles.findAll", Styles.class)
.getResultList();
if (list == null || list.isEmpty()) {
list = null;
}
} finally {
em.close();
}
return list;
}
the JPA I am using is
#Entity
#Table(name = "styles")
#NamedQueries({
#NamedQuery(name = "Styles.findAll", query = "SELECT s FROM Styles s"),
#NamedQuery(name = "Styles.findById", query = "SELECT s FROM Styles s WHERE s.id = :id"),
#NamedQuery(name = "Styles.findByCatId", query = "SELECT s FROM Styles s WHERE s.catId = :catId"),
#NamedQuery(name = "Styles.findByStyleName", query = "SELECT s FROM Styles s WHERE s.styleName = :styleName"),
#NamedQuery(name = "Styles.findByLastMod", query = "SELECT s FROM Styles s WHERE s.lastMod = :lastMod")})
public class Styles implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#NotNull
#Column(name = "cat_id")
private int catId;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 255)
#Column(name = "style_name")
private String styleName;
#Basic(optional = false)
#NotNull
#Column(name = "last_mod")
#Temporal(TemporalType.TIMESTAMP)
private Date lastMod;
public Styles() {
}
public Styles(Integer id) {
this.id = id;
}
public Styles(Integer id, int catId, String styleName, Date lastMod) {
this.id = id;
this.catId = catId;
this.styleName = styleName;
this.lastMod = lastMod;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public int getCatId() {
return catId;
}
public void setCatId(int catId) {
this.catId = catId;
}
public String getStyleName() {
return styleName;
}
public void setStyleName(String styleName) {
this.styleName = styleName;
}
public Date getLastMod() {
return lastMod;
}
public void setLastMod(Date lastMod) {
this.lastMod = lastMod;
}
#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 Styles)) {
return false;
}
Styles other = (Styles) 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 "Service.Styles[ id=" + id + " ]";
}
}

You can use #OrderBy annotation
https://www.logicbig.com/tutorials/java-ee-tutorial/jpa/order-by-annotation.html

Just create another query:
#NamedQuery(name = "Styles.findAll", query = "SELECT s FROM Styles s ORDER BY s.name")
And why are you filtering in the code when you can add a query with a where condition?

Related

JPQL count Parent Objects on Multiple Children Match in OneToMany Relationship

In a JavaEE JPA web application, Feature entity has bidirectional ManyToOne relationship with Patient Entity. I want to write a query to count the number of Patients who have one or more matching criteria features. I use EclipseLink as the Persistence Provider.
For example, I want to count the number of patients who have a feature with 'variableName' = 'Sex' and 'variableData' = 'Female' and another feature with 'variableName' = 'smoking' and 'variableData' = 'yes'.
How can I write a JPQL query to get the count of patients?
After the first answer, I tried this Query does not give any results as expected.
public void querySmokingFemales(){
String j = "select count(f.patient) from Feature f "
+ "where ((f.variableName=:name1 and f.variableData=:data1)"
+ " and "
+ " (f.variableName=:name2 and f.variableData=:data2))";
Map m = new HashMap();
m.put("name1", "sex");
m.put("data1", "female");
m.put("name2", "smoking");
m.put("data2", "yes");
count = getFacade().countByJpql(j, m);
}
The Patient entity is as follows.
#Entity
public class Patient implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
#OneToMany(mappedBy = "patient")
private List<Feature> features;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#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 Patient)) {
return false;
}
Patient other = (Patient) 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 "entity.Patient[ id=" + id + " ]";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Feature> getFeatures() {
return features;
}
public void setFeatures(List<Feature> features) {
this.features = features;
}
}
This is the Feature Entity.
#Entity
public class Feature implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String variableName;
private String variableData;
#ManyToOne
private Patient patient;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#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 Feature)) {
return false;
}
Feature other = (Feature) 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 "entity.Feature[ id=" + id + " ]";
}
public String getVariableName() {
return variableName;
}
public void setVariableName(String variableName) {
this.variableName = variableName;
}
public String getVariableData() {
return variableData;
}
public void setVariableData(String variableData) {
this.variableData = variableData;
}
public Patient getPatient() {
return patient;
}
public void setPatient(Patient patient) {
this.patient = patient;
}
}
For single feature counts you can use this
select count(f.patient) from Feature f where f.variableName=:name and f.variableData:=data
Two feature counts
select count(distinct p) from Patient p, Feature f1, Feature f2
where
p.id=f1.patient.id and p.id=f2.patient.id and
f1.variableName=:name1 and f1.variableData:=data1 and
f2.variableName=:name2 and f2.variableData:=data2
Multiple feature counts solution is a bit tricky. org.springframework.data.jpa.domain.Specification can be used
public class PatientSpecifications {
public static Specification<Patient> hasVariable(String name, String data) {
return (root, query, builder) -> {
Subquery<Fearure> subquery = query.subquery(Fearure.class);
Root<Fearure> feature = subquery.from(Fearure.class);
Predicate predicate1 = builder.equal(feature.get("patient").get("id"), root.get("id"));
Predicate predicate2 = builder.equal(feature.get("variableName"), name);
Predicate predicate3 = builder.equal(feature.get("variableData"), data);
subquery.select(operation).where(predicate1, predicate2, predicate3);
return builder.exists(subquery);
}
}
}
Then your PatientRepository have to extend org.springframework.data.jpa.repository.JpaSpecificationExecutor<Patient>
#Repository
public interface PatientRepository
extends JpaRepository<Patient, Long>, JpaSpecificationExecutor<Patient> {
}
Your service method:
#Service
public class PatientService {
#Autowired
PatientRepository patientRepository;
//The larger map is, the more subqueries query would involve. Try to avoid large map
public long countPatiens(Map<String, String> nameDataMap) {
Specification<Patient> spec = null;
for(Map.Entry<String, String> entry : nameDataMap.entrySet()) {
Specification<Patient> tempSpec = PatientSpecifications.hasVariable(entry.getKey(), entry.getValue());
if(spec != null)
spec = Specifications.where(spec).and(tempSpec);
else spec = tempSpec;
}
Objects.requireNonNull(spec);
return patientRepository.count(spec);
}
}
We also handled same situation for two feature and after extracting the IDs, we used a nested loops after and counting the number of common count. It was resource intensive and this two feature query in the answer helped a lot.
May need to redesign the Class Structure so that querying is easier.

Bidrectional #OneToMany relation with a composite key

I have been trying to create a bidirectional #OneToMany relation with composite keys but some pieces are missing or wrong.
I have a draft entity which holds a list of sub draft entities.
Here is what I got:
#Entity
#Table(name = "draft")
#IdClass(Pk.class)
public class Draft {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
protected Long id;
#Id
protected Integer rev;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "draft")
List<SubDraft> subDrafts = new ArrayList<SubDraft>();
// getters / setters omitted
}
#Entity
#Table(name = "sub_draft")
#IdClass(PK.class)
public class DraftToDoDAO {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
protected Long id;
#Id
protected Integer rev;
#ManyToOne(fetch = FetchType.LAZY)
#PrimaryKeyJoinColumns({
#PrimaryKeyJoinColumn(name = "draft_id", referencedColumnName = "id"),
#PrimaryKeyJoinColumn(name = "draft_rev", referencedColumnName = "rev")
})
protected DraftDAO draft;
// getters / setters omitted
}
public class PK implements Serializable {
protected Long id;
protected Integer rev;
public PK() {
}
public PK(Long id, Integer rev) {
this.id = id;
this.rev = rev;
}
public Long getId() {
return id;
}
public Integer getRev() {
return rev;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((rev == null) ? 0 : rev.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MetaDataDAO other = (MetaDataDAO) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (rev == null) {
if (other.rev != null)
return false;
} else if (!rev.equals(other.rev))
return false;
return true;
}
}
I have no problems saving a draft with a list of sub drafts but the relation is not created both ways.
In the sub draft table the SchemaTool (DataNucleus) creates a column named draft_id but it is empty. And I wonder why it is not creating the columns I specified (draft_id, draft_rev) and settles the relation there.
I have search a lot for an answer but just can not get thing to work.
Your help is appreciated!
Thanks.
EDIT!
Here is the actual persistence code:
public Draft create(Draft draft, SubDraft subDraft) {
EntityManager em = PersistenceHelper.getEntityManager();
draft.setCreated(Calendar.getInstance());
// This should do it
draft.setSubDraft(subDraft);
subDraft.setDraft(draft);
em.persist(draft);
em.close();
return draft;
}
Some where along the line of code this subDraft attribute was nilled and therefore is did not work.

jpa named query using foreign key is not working

MY Entity class
#Entity
#Table(catalog = "", schema = "MYIS")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Answers.findAll", query = "SELECT a FROM Answers a"),
#NamedQuery(name = "Answers.findByAid", query = "SELECT a FROM Answers a WHERE a.aid = :aid"),
#NamedQuery(name ="Anaswers.findByqid", query ="SELECT a FROM Answers a WHERE a.answerQid.qid = :x"),
#NamedQuery(name = "Answers.findByAnsValue", query = "SELECT a FROM Answers a WHERE a.ansValue = :ansValue"),
#NamedQuery(name = "Answers.findByAnsDate", query = "SELECT a FROM Answers a WHERE a.ansDate = :ansDate")})
public class Answers implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Column(nullable = false)
private Integer aid;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 4000)
#Column(name = "ANS_VALUE", nullable = false, length = 4000)
private String ansValue;
#Basic(optional = false)
#NotNull
#Column(name = "ANS_DATE", nullable = false)
#Temporal(TemporalType.TIMESTAMP)
private Date ansDate;
#JoinColumn(name = "A_USERID", referencedColumnName = "USERID", nullable = false)
#ManyToOne(optional = false)
private Users aUserid;
#JoinColumn(name = "ANSWER_QID", referencedColumnName = "QID", nullable = false)
#ManyToOne(optional = false)
private Questions answerQid;
#JoinColumn(name = "A_GROUPID", referencedColumnName = "GID", nullable = false)
#ManyToOne(optional = false)
private Groups aGroupid;
public Answers() {
}
public Answers(Integer aid) {
this.aid = aid;
}
public Answers(Integer aid, String ansValue, Date ansDate) {
this.aid = aid;
this.ansValue = ansValue;
this.ansDate = ansDate;
}
public Integer getAid() {
return aid;
}
public void setAid(Integer aid) {
this.aid = aid;
}
public String getAnsValue() {
return ansValue;
}
public void setAnsValue(String ansValue) {
this.ansValue = ansValue;
}
public Date getAnsDate() {
return ansDate;
}
public void setAnsDate(Date ansDate) {
this.ansDate = ansDate;
}
public Users getAUserid() {
return aUserid;
}
public void setAUserid(Users aUserid) {
this.aUserid = aUserid;
}
public Questions getAnswerQid() {
return answerQid;
}
public void setAnswerQid(Questions answerQid) {
this.answerQid = answerQid;
}
public Groups getAGroupid() {
return aGroupid;
}
public void setAGroupid(Groups aGroupid) {
this.aGroupid = aGroupid;
}
#Override
public int hashCode() {
int hash = 0;
hash += (aid != null ? aid.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 Answers)) {
return false;
}
Answers other = (Answers) object;
if ((this.aid == null && other.aid != null) || (this.aid != null && !this.aid.equals(other.aid))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.entity.Answers[ aid=" + aid + " ]";
}
}
MY SESSION FACADE
import com.entity.Answers;
import com.entity.Groups;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
/**
*
* #author krishna teja
*/
#Stateless
public class AnswersFacade extends AbstractFacade<Answers> implements AnswersFacadeLocal {
#PersistenceContext(unitName = "My_communityPU")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}
public AnswersFacade() {
super(Answers.class);
}
public List<Answers> getdataByQid(Long qid){
Query query=em.createNamedQuery("Answers.findByqid");
query.setParameter(1, qid);
List<Answers> a =query.getResultList();
return a;
}
}
My managed bean
#PostConstruct
public void init(){
questions = questionsFacade.findAll();
ansList = answersFacade.getdataByQid(g);
}
I am getting following exception
at com.ejb.AnswersFacade.getdataByQid(AnswersFacade.java:36)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
I have created named query for the foreign key attribute answerQid and and created method in the sessionfacade and tried to access it in the managed bean the default methods work perfectly but my method for query is not working please help me
Looks like a simple typo. Named query is defined as Anaswers.findByqid, but used as Answers.findByqid.

Why JPA doesnt generate a join junction table in this case

I have two tables Students and Books , with a many to many relationship. The code of both are given below. Now when I try to run the code I get the error.
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'acme.book_stud' doesn't exist
Error Code: 1146
Call: INSERT INTO book_stud (idStudents, idBooks) VALUES (?, ?)
bind => [2 parameters bound]
It seems like JPA is trying to write to a juction table which does not exist (in this case it assumes a junction table books_students is already created so it doesnt create one.). It works if I create a books_students but I dont want to do that since its JPA responsibility to create it. Is there a way in which I could explicitly tell it to create one. ? (I am taking a wild guess here - but I guess when creating a persitance unit I specified "none" I think thats why it didnt create that table . Am I correct ? Anyways here are my Student and Books Classes
BOOKS CLASS
#Entity
#Table(name = "books")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Books.findAll", query = "SELECT b FROM Books b"),
#NamedQuery(name = "Books.findByIdBooks", query = "SELECT b FROM Books b WHERE b.idBooks = :idBooks"),
#NamedQuery(name = "Books.findByBookName", query = "SELECT b FROM Books b WHERE b.bookName = :bookName"),
#NamedQuery(name = "Books.findByBookType", query = "SELECT b FROM Books b WHERE b.bookType = :bookType")})
public class Books implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "idBooks")
private String idBooks;
#Size(max = 45)
#Column(name = "BookName")
private String bookName;
#Size(max = 45)
#Column(name = "BookType")
private String bookType;
/******************************************ADDED **********************/
#ManyToMany
#JoinTable(name = "book_stud",
joinColumns = { #JoinColumn(name = "idStudents") },
inverseJoinColumns = { #JoinColumn(name = "idBooks") })
/**************************************ENDED*****************************/
public Books() {
}
public Books(String idBooks) {
this.idBooks = idBooks;
}
public String getIdBooks() {
return idBooks;
}
public void setIdBooks(String idBooks) {
this.idBooks = idBooks;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getBookType() {
return bookType;
}
public void setBookType(String bookType) {
this.bookType = bookType;
}
#Override
public int hashCode() {
int hash = 0;
hash += (idBooks != null ? idBooks.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 Books)) {
return false;
}
Books other = (Books) object;
if ((this.idBooks == null && other.idBooks != null) || (this.idBooks != null && !this.idBooks.equals(other.idBooks))) {
return false;
}
return true;
}
#Override
public String toString() {
return "domain.Books[ idBooks=" + idBooks + " ]";
}
}
STUDENT CLASS
#Entity
#Table(name = "students")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "StudentEnroll.findAll", query = "SELECT s FROM StudentEnroll s"),
#NamedQuery(name = "StudentEnroll.findByIdStudents", query = "SELECT s FROM StudentEnroll s WHERE s.idStudents = :idStudents"),
#NamedQuery(name = "StudentEnroll.findByName", query = "SELECT s FROM StudentEnroll s WHERE s.name = :name"),
#NamedQuery(name = "StudentEnroll.findByRoll", query = "SELECT s FROM StudentEnroll s WHERE s.roll = :roll"),
#NamedQuery(name = "StudentEnroll.findBySsn", query = "SELECT s FROM StudentEnroll s WHERE s.ssn = :ssn"),
#NamedQuery(name = "StudentEnroll.findByProgram", query = "SELECT s FROM StudentEnroll s WHERE s.program = :program")})
public class StudentEnroll implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 40)
#Column(name = "idStudents")
private String idStudents;
#Size(max = 45)
#Column(name = "Name")
private String name;
#Column(name = "Roll")
private Integer roll;
#Column(name = "SSN")
private Integer ssn;
#Size(max = 45)
#Column(name = "Program")
private String program;
#JoinColumn(name = "CustomerID", referencedColumnName = "UserID")
#ManyToOne
private Customer customerID;
//#OneToMany(mappedBy = "studentRoll")
#OneToMany(mappedBy = "studentRoll",cascade = CascadeType.REMOVE)//added REMOVE
private Collection<Subject> subjectCollection;
/**************************ADDED*****************************/
#ManyToMany
#JoinTable(name = "book_stud",
joinColumns = { #JoinColumn(name = "idBooks") },
inverseJoinColumns = { #JoinColumn(name = "idStudents") })
/**********************************END**********************/
public StudentEnroll() {
}
public StudentEnroll(String idStudents) {
this.idStudents = idStudents;
}
public String getIdStudents() {
return idStudents;
}
public void setIdStudents(String idStudents) {
this.idStudents = idStudents;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getRoll() {
return roll;
}
public void setRoll(Integer roll) {
this.roll = roll;
}
public Integer getSsn() {
return ssn;
}
public void setSsn(Integer ssn) {
this.ssn = ssn;
}
public String getProgram() {
return program;
}
public void setProgram(String program) {
this.program = program;
}
public Customer getCustomerID() {
return customerID;
}
public void setCustomerID(Customer customerID) {
this.customerID = customerID;
}
#XmlTransient
public Collection<Subject> getSubjectCollection() {
return subjectCollection;
}
public void setSubjectCollection(Collection<Subject> subjectCollection) {
this.subjectCollection = subjectCollection;
}
#Override
public int hashCode() {
int hash = 0;
hash += (idStudents != null ? idStudents.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 StudentEnroll)) {
return false;
}
StudentEnroll other = (StudentEnroll) object;
if ((this.idStudents == null && other.idStudents != null) || (this.idStudents != null && !this.idStudents.equals(other.idStudents))) {
return false;
}
return true;
}
#Override
public String toString() {
return "domain.StudentEnroll[ idStudents=" + idStudents + " ]";
}
}

EclipseLink GeneratedValue null on postgres only on one entity

I have a rather weird case. I have some entities generated with netbeans and i can persist all except one. I see no difference in the database nor in the entity class. Can someone help me, here is my entity class , database, and error that i am receiving
CREATE TABLE objekat
(
id_objekat bigserial NOT NULL,
id_opstina serial NOT NULL,
naziv character varying(50) NOT NULL,
kapacitet character varying(50),
adresa character varying(100),
lokacija_sirina double precision,
lokacija_duzina double precision,
opis character varying(500),
korisnicko_ime character varying(50),
sifra character varying(50),
maks_broj_slike integer,
absolute_path_logo character varying(255),
CONSTRAINT objekat_pkey PRIMARY KEY (id_objekat),
CONSTRAINT fkobjekat924176 FOREIGN KEY (id_opstina)
REFERENCES opstina (id_opstina) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)
WITH (
OIDS=FALSE
);
and this is my entity bean.
#Entity
#Table(name = "objekat")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Objekat.findAll", query = "SELECT o FROM Objekat o"),
#NamedQuery(name = "Objekat.findByIdObjekat", query = "SELECT o FROM Objekat o WHERE o.idObjekat = :idObjekat"),
#NamedQuery(name = "Objekat.findByNaziv", query = "SELECT o FROM Objekat o WHERE upper (o.naziv) like upper(:naziv)"),
#NamedQuery(name = "Objekat.findByNazivAndOpstina", query = "SELECT o FROM Objekat o inner join o.idOpstina op WHERE upper (o.naziv) like upper(:naziv) and op.idOpstina = :idOpstina"),
#NamedQuery(name = "Objekat.findByKapacitet", query = "SELECT o FROM Objekat o WHERE o.kapacitet = :kapacitet"),
#NamedQuery(name = "Objekat.findByAdresa", query = "SELECT o FROM Objekat o WHERE o.adresa = :adresa"),
#NamedQuery(name = "Objekat.findByLokacijaSirina", query = "SELECT o FROM Objekat o WHERE o.lokacijaSirina = :lokacijaSirina"),
#NamedQuery(name = "Objekat.findByLokacijaDuzina", query = "SELECT o FROM Objekat o WHERE o.lokacijaDuzina = :lokacijaDuzina")})
public class Objekat implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id_objekat",columnDefinition = "BIGSERIAL")
private Long idObjekat;
#Size(max = 255)
#Column(name = "absolute_path_logo")
private String absolutePathLogo;
#OneToMany( mappedBy = "objekatidObjekat")
private List<DogadjajObjekat> dogadjajObjekatList;
#OneToMany( mappedBy = "objekatidObjekat")
private List<SlikeLokacijaObjekat> slikeLokacijaObjekatList;
#OneToMany( mappedBy = "idObjekat")
private List<RasporedObjekat> rasporedObjekatList;
#Column(name = "maks_broj_slike")
private Integer maksBrojSlike;
#Size(max = 50)
#Column(name = "korisnicko_ime")
private String korisnickoIme;
#Size(max = 50)
#Column(name = "sifra")
private String sifra;
#Size(max = 500)
#Column(name = "opis")
private String opis;
// #Max(value=?) #Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
#Column(name = "lokacija_sirina")
private Double lokacijaSirina;
#Column(name = "lokacija_duzina")
private Double lokacijaDuzina;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 50)
#Column(name = "naziv")
private String naziv;
#Size(max = 50)
#Column(name = "kapacitet")
private String kapacitet;
#Size(max = 100)
#Column(name = "adresa")
private String adresa;
#JoinTable(name = "tip_objekta_objekat", joinColumns = {
#JoinColumn(name = "objekatid_objekat", referencedColumnName = "id_objekat")}, inverseJoinColumns = {
#JoinColumn(name = "tip_objektaid_tip_objekta", referencedColumnName = "id_tip_objekta")})
#ManyToMany
private List<TipObjekta> tipObjektaList;
#JoinColumn(name = "id_opstina", referencedColumnName = "id_opstina")
#ManyToOne(optional = false)
private Opstina idOpstina;
public Objekat() {
}
public Objekat(Long idObjekat) {
this.idObjekat = idObjekat;
}
public Objekat(Long idObjekat, String naziv) {
this.idObjekat = idObjekat;
this.naziv = naziv;
}
public Long getIdObjekat() {
return idObjekat;
}
public void setIdObjekat(Long idObjekat) {
this.idObjekat = idObjekat;
}
public String getNaziv() {
return naziv;
}
public void setNaziv(String naziv) {
this.naziv = naziv;
}
public String getKapacitet() {
return kapacitet;
}
public void setKapacitet(String kapacitet) {
this.kapacitet = kapacitet;
}
public String getAdresa() {
return adresa;
}
public void setAdresa(String adresa) {
this.adresa = adresa;
}
#XmlTransient
public List<TipObjekta> getTipObjektaList() {
return tipObjektaList;
}
public void setTipObjektaList(List<TipObjekta> tipObjektaList) {
this.tipObjektaList = tipObjektaList;
}
public Opstina getIdOpstina() {
return idOpstina;
}
public void setIdOpstina(Opstina idOpstina) {
this.idOpstina = idOpstina;
}
#Override
public int hashCode() {
int hash = 0;
hash += (idObjekat != null ? idObjekat.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 Objekat)) {
return false;
}
Objekat other = (Objekat) object;
if ((this.idObjekat == null && other.idObjekat != null) || (this.idObjekat != null && !this.idObjekat.equals(other.idObjekat))) {
return false;
}
return true;
}
#Override
public String toString() {
return "rs.dzetSet.entiteti.Objekat[ idObjekat=" + idObjekat + " ]";
}
public String getOpis() {
return opis;
}
public void setOpis(String opis) {
this.opis = opis;
}
public Double getLokacijaSirina() {
return lokacijaSirina;
}
public void setLokacijaSirina(Double lokacijaSirina) {
this.lokacijaSirina = lokacijaSirina;
}
public Double getLokacijaDuzina() {
return lokacijaDuzina;
}
public void setLokacijaDuzina(Double lokacijaDuzina) {
this.lokacijaDuzina = lokacijaDuzina;
}
public String getKorisnickoIme() {
return korisnickoIme;
}
public void setKorisnickoIme(String korisnickoIme) {
this.korisnickoIme = korisnickoIme;
}
public String getSifra() {
return sifra;
}
public void setSifra(String sifra) {
this.sifra = sifra;
}
public Integer getMaksBrojSlike() {
return maksBrojSlike;
}
public void setMaksBrojSlike(Integer maksBrojSlike) {
this.maksBrojSlike = maksBrojSlike;
}
public void pocevajMaksBrojSlike(){
this.maksBrojSlike++;
}
public String getAbsolutePathLogo() {
return absolutePathLogo;
}
public void setAbsolutePathLogo(String absolutePathLogo) {
this.absolutePathLogo = absolutePathLogo;
}
#XmlTransient
public List<RasporedObjekat> rasporedObjekatListPrePodne(){
List<RasporedObjekat> rez = new ArrayList<RasporedObjekat>();
if(rasporedObjekatList==null){
rasporedObjekatList = new ArrayList<RasporedObjekat>();
}
for(RasporedObjekat ro:rasporedObjekatList){
if(!ro.getVecernjiProgram()){
rez.add(ro);
}
}
return rez;
}
#XmlTransient
public List<RasporedObjekat> rasporedObjekatListPoslePodne(){
List<RasporedObjekat> rez = new ArrayList<RasporedObjekat>();
if(rasporedObjekatList==null){
rasporedObjekatList = new ArrayList<RasporedObjekat>();
}
for(RasporedObjekat ro:rasporedObjekatList){
if(ro.getVecernjiProgram()){
rez.add(ro);
}
}
return rez;
}
#XmlTransient
public List<DogadjajObjekat> getDogadjajObjekatList() {
return dogadjajObjekatList;
}
public void setDogadjajObjekatList(List<DogadjajObjekat> dogadjajObjekatList) {
this.dogadjajObjekatList = dogadjajObjekatList;
}
#XmlTransient
public List<SlikeLokacijaObjekat> getSlikeLokacijaObjekatList() {
return slikeLokacijaObjekatList;
}
public void setSlikeLokacijaObjekatList(List<SlikeLokacijaObjekat> slikeLokacijaObjekatList) {
this.slikeLokacijaObjekatList = slikeLokacijaObjekatList;
}
#XmlTransient
public List<RasporedObjekat> getRasporedObjekatList() {
return rasporedObjekatList;
}
public void setRasporedObjekatList(List<RasporedObjekat> rasporedObjekatList) {
this.rasporedObjekatList = rasporedObjekatList;
}
and i persist it in a rather normal way, or i just think so.
utx.begin();
if(noviObjekat.getIdObjekat() == null){
em.persist(noviObjekat);
}else{
em.merge(noviObjekat);
}
utx.commit();
and i get a pretty weird error
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.0.v20110604-r9504): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: org.postgresql.util.PSQLException: ERROR: null value in column "id_opstina" violates not-null constraint
Error Code: 0
Call: INSERT INTO objekat (absolute_path_logo, adresa, kapacitet, korisnicko_ime, lokacija_duzina, lokacija_sirina, maks_broj_slike, naziv, opis, sifra, id_opstina) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
bind => [11 parameters bound]
Query: InsertObjectQuery(rs.dzetSet.entiteti.Objekat[ idObjekat=null ])
}
You set a generator on the field for "id_objekat" but the exception is for the not-null constraint on "id_opstina". You will need to set this field yourself or use a returning policy to get it instead:
http://wiki.eclipse.org/Using_EclipseLink_JPA_Extensions_(ELUG)#Using_EclipseLink_JPA_Extensions_for_Returning_Policy