my Model Entity FrameWork :
public partial class T02
{
public long ID { get; set; }
public int F01 { get; set; }
}
Table : T02
------------------------
id[Key,identity] F01
------------------------
1 a
2 b
====================================================
i have a button > Code
public void Button_Click(object Sender, EventArgs e)
{
T02 T1 = new T02 { ID = 1, F01 = "x" };
T02 T2 = new T02 { ID = 2, F01 = "y" };
T02 T3 = new T02 { ID = 0, F01 = "g" };
T02 T4 = new T02 { ID = 0, F01 = "h" };
// How ID > 1 2 Update in Table &
// because not in table, > g , h > automatic add to Table
// ???
}
my problem is : i not ontime update and if T02.ID not on the table automatic added..
Is it possible that I do added to table Records Without id and i do Update Records With id
i worked c#.NET 4.5 . Thanks
Add this method to your Context class:
protected virtual void InsertOrUpdate<T>(T entity, long id)
{
if (id == default(int))
this.Set<T>().Add(entity);
else
this.Entry(entity).State = EntityState.Modified;
}
Which can be used something like this:
public void Button_Click(object Sender, EventArgs e)
{
T02 T1 = new T02 { ID = 1, F01 = "x" };
T02 T2 = new T02 { ID = 2, F01 = "y" };
T02 T3 = new T02 { ID = 0, F01 = "g" };
T02 T4 = new T02 { ID = 0, F01 = "h" };
using(var context = new MyDbContext())
{
context.InsertOrUpdate(T1, T1.ID);
context.InsertOrUpdate(T2, T2.ID);
context.InsertOrUpdate(T3, T3.ID);
context.InsertOrUpdate(T4, T4.ID);
}
}
Once this is working you can consider implementing a standard interface across all of your POCO classes that exposes the ID property so that you no longer have to pass ID into the method:
public interface IId
{
long ID { get; }
}
public partial class T02 : IId
{
public long ID { get; set; }
public int F01 { get; set; }
}
which gives you a neater method in your Context
protected virtual void InsertOrUpdate<T>(T entity) where T : IId
{
if (entity.ID == default(int))
this.Set<T>().Add(entity);
else
this.Entry(entity).State = EntityState.Modified;
}
Related
I have B class that has a class A as member. The LiteDb store it correctly as I see in LiteDB Studio. "As" collection is also OK. Why is it not right in the deserialization? Class A has a BsonCtor. B also
namespace ConsoleAppTestDeserializatioBug {
class Program {
public class A {
public A() { A_ID = ObjectId.NewObjectId(); }
[BsonCtor]
public A(ObjectId id, string name) { A_ID = id; Name = name; }
[BsonId]
public ObjectId A_ID { get; set; }
public string Name { get; set; }
public const string CollectionName = "As";
}
public class B {
public const string CollectionName = "Bs";
public B() { B_ID = ObjectId.NewObjectId(); }
[BsonCtor]
public B(ObjectId id, int dummy, A a) { B_ID = id; Dummy = dummy; aObj = a;}
[BsonId]
public ObjectId B_ID { get; set; }
public int Dummy { get; set; }
[BsonRef(A.CollectionName)]
public A aObj { get; set; }
}
private LiteDatabase _LiteDatabase;
static void Main(string[] args) {
var p = new Program();
p.Test();
}
private void Test() {
A a = new A(); // Create my Object
a.Name = "Name123";
var initialId = a.A_ID;
B b = new B();
b.Dummy = 123;
b.aObj = a;
_LiteDatabase = new LiteDatabase(new ConnectionString(#"C:\Temp\tst1.db") { Connection = ConnectionType.Shared });
ILiteCollection<A> aas = _LiteDatabase.GetCollection<A>(A.CollectionName);
aas.Insert(a);
ILiteCollection<B> bs = _LiteDatabase.GetCollection<B>(B.CollectionName);
bs.Insert(b);
// Get in the DB
var bb = bs.FindAll().ToArray()[0];
var aa = bb.aObj;
var aaid = aa.A_ID;
if (aaid == initialId) { Console.WriteLine("Id is correct");}
var aname = aa.Name; // aname i s null!!!!! and why
}
}
}
I found an answer in LiteSB DbRef
I must just add an "include" in my query:
var bb = bs.Include(x => x.aObj).FindAll().ToArray()[0];
Please be so kind to help me understand why, by running attached code, I have multiple records been written in parent table from my data base (MySQL) with corresponding to a record in related table, although the set up in Java code is for one to one relation (i.e. one records in parent corresponding to only one record in other related table.
I am at your disposal for any questions you might have on the subject.
many thank for support
petrisor
public class Main {
public static void main(String[] args) {
createParkingLot();
AddEmployees(1);
AddEmployees(2);
}
public static void createParkingLot(){
EntityManagerFactory emf =
Persistence.createEntityManagerFactory("java2curs4e1PU");
EntityManager em = emf.createEntityManager();
ParkingLot p1= new ParkingLot();
p1.setParking_lot_no(1);
try{
em.getTransaction().begin();
em.persist(p1);
em.getTransaction().commit();
} finally {
em.close();
emf.close();
}
}
public static void AddEmployees(int employee_number){
EntityManagerFactory emf =
Persistence.createEntityManagerFactory("java2curs4e1PU");
EntityManager em = emf.createEntityManager();
ParkingLot p2 = em.find(ParkingLot.class,1);
Employee a1 = new Employee();
a1.setEmployee_name("Employee_name_#"+employee_number);
a1.setParking_lot(p2);
try{
em.getTransaction().begin();
em.persist(a1);
em.getTransaction().commit();
} finally {
em.close();
emf.close();
}
}
}
+++++++++++++++++++++++++++++
related entities description:
+++++++++++++++++++++++++++++
Entity Employee
+++++++++++++++++++++++++++++
#Entity
#Table(name = "employees")
public class Employee implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String employee_name;
#OneToOne(cascade = CascadeType.ALL,optional = false,fetch =
FetchType.LAZY)
#JoinColumn(name = "id_parking_lot")
private ParkingLot parking_lot;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getEmployee_name() {
return employee_name;
}
public void setEmployee_name(String employee_name) {
this.employee_name = employee_name;
}
public ParkingLot getParking_lot() {
return parking_lot;
}
public void setParking_lot(ParkingLot parking_lot) {
this.parking_lot = parking_lot;
}
#Override
public String toString() {
return "Employee{" + "id=" + id + ", name=" + employee_name + ",
parking lot=" + parking_lot + '}';
}
}
++++++++++++++++++++++++++++
Entity ParkingLot:
++++++++++++++++++++++++++++
#Entity
#Table(name = "parking_lots")
public class ParkingLot implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY )
private int id;
private int parking_lot_no;
#OneToOne(cascade = CascadeType.ALL,fetch = FetchType.LAZY,optional =
false,mappedBy = "parking_lot")
private Employee employee;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getParking_lot_no() {
return parking_lot_no;
}
public void setParking_lot_no(int parking_lot_no) {
this.parking_lot_no = parking_lot_no;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
#Override
public String toString() {
return "ParkingLot{" + "id=" + id + ", parking lot number=" +
parking_lot_no + '}';
}
}
Normally I would expect the program to through an exception as I tried to insert another Employee (Employee_name_#2) with the same parking lot (id 1).
Instead in table employees I found that I have 2 employees with same parking lot.
i have two tables:
area (
id int PK autoincrement
code varchar
)
products (
id int PK autoincrement
area_id int
)
And the objets are defined like this:
class Product {
...
#JoinColumn(name = "area_id", referencedColumnName = "id")
#ManyToOne
#Expose
private Area area;
...
}
This works fine but I want that area to be a String with the code used in the table area column code.
class Product {
...
???
private String area;
...
}
What should be the annotations to make this work?
Thanks!
Try to use a combination of #SecondaryTable and #Column annotations. Something like this:
#Entity
#SecondaryTable(name="area", pkJoinColumns=#PrimaryKeyJoinColumn(name="id", referencedColumnName="area_id"))
class Product {
...
#Column(name="code", table = "area")
private String code;
...
}
If there is some poor soul with the same problem, here is how I did it:
Using transformers. So the field area is defined like this:
#Transformation(fetch = FetchType.EAGER, optional = false)
#ReadTransformer(transformerClass = AreaAttributeTransformer.class)
#WriteTransformers({
#WriteTransformer(
transformerClass = AreaFieldTransformer.class,
column = #Column(name = "area_id", nullable = false))
})
#Expose
private String area;
Then those clases work like this:
AreaAttributeTransformer
public class AreaAttributeTransformer implements AttributeTransformer {
private AbstractTransformationMapping mapping;
#Override
public void initialize(AbstractTransformationMapping abstractTransformationMapping) {
this.mapping = abstractTransformationMapping;
}
#Override
public Object buildAttributeValue(Record record, Object o, Session session) {
for (DatabaseField field : mapping.getFields()) {
if (field.getName().contains("area_id")) {
EntityManager em = MyEntityManagerFactory.getENTITY_MANAGER_FACTORY().createEntityManager();
List results = em.createNamedQuery("Areas.findById")
.setParameter("id", record.get(field))
.getResultList();
if (results.size() > 0)
return ((Area) results.get(0)).getCode();
}
}
return null;
}
}
AreaFieldTransformer
public class AreaFieldTransformer implements FieldTransformer {
private AbstractTransformationMapping mapping;
#Override
public void initialize(AbstractTransformationMapping abstractTransformationMapping) {
this.mapping = abstractTransformationMapping;
}
#Override
public Object buildFieldValue(Object o, String s, Session session) {
if (o instanceof RouSub) {
EntityManager em = MyEntityManagerFactory.getENTITY_MANAGER_FACTORY().createEntityManager();
List results = em.createNamedQuery("Area.findByCode")
.setParameter("area", ((Area) o).getCode())
.getResultList();
if (results.size() > 0)
return ((Area)results.get(0)).getId();
}
return null;
}
}
Hi i having problem with deleting of an entity. The entitymanager would not remove the entity. Do anyone see the error in the code?
Error message:
java.lang.AssertionError:
Expected :null
Actual :Account{id=1, customer=Customer{customerId=1, firstName='Kim', lastName='Pedersen', email='kim#yahoo.no', phoneNumber='90045870', birth=1980-11-05 00:00:00.0}, login= 'Login{Id=1, username='kimPedda', password='kimSimDimSum'}}
#Entity
#NamedQuery(name = "Account.getAll", query = "select a from Account a")
#SequenceGenerator(name = "SEQ_ACC", initialValue = 50)
public class Account {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_ACC")
private int id;
#OneToOne(cascade = CascadeType.ALL)//, fetch = FetchType.EAGER)
#JoinColumn(name = "FK_CUSTOMER")
private Customer customer;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "FK_LOGIN")
private Login login;
/*
-------------------------------------------
CONSTRUCTORS
-------------------------------------------
*/
public Account(Customer customer, Login login) {
this.customer = customer;
this.login = login;
}
public Account() {
}
// ======================================
// = GET AND SET =
// ======================================
public Customer getCustomer() {
return customer;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public Login getLogin() {
return login;
}
public void setLogin(Login login) {
this.login = login;
}
// ======================================
// = TO STRING =
// ======================================
#Override
public String toString() {
return "Account{" +
"id=" + id +
", customer=" + customer +
", login= '" + login +
'}';
}
}
public class JpaAccountDao implements AccountDao {
#PersistenceContext(unitName = "account")
private EntityManager entityManager;
public JpaAccountDao() {
}
public JpaAccountDao(EntityManager entityManager){
this.entityManager = entityManager;
}
#Override
public Account persist(Account account) {
if( account == null )
throw new IllegalArgumentException("No account could be created!");
entityManager.persist(account);
return account;
}
#Override
public Boolean delete(int id) {
if( id != 0) {
Account account = entityManager.find(Account.class,id);
entityManager.remove(account);
return true;
}
throw new IllegalArgumentException(String.format("Account with id-nr:{%d] could not be deleted =C ", id ));
}
#Override
public Account findById(int id) {
if( id <= 0 )
throw new IllegalArgumentException("No id was found!");
return entityManager.find(Account.class, id);
}
#Override
public List<Account> getAll() {
TypedQuery<Account> query = entityManager.createNamedQuery("Account.getAll", Account.class);
return query.getResultList();
}
}
public class AccountServiceIT {
private EntityManager entityManager;
private EntityManagerFactory factory;
private JpaAccountDao jpaAccountDao;
private JpaCustomerDao jpaCustomerDao;
private CustomerTestCase customerTestCase;
private JpaLoginDao jpaLoginDao;
private Account account;
private Account account2;
#Before
public void setup() throws Exception {
factory = Persistence.createEntityManagerFactory("TEST");
entityManager = factory.createEntityManager();
jpaAccountDao = new JpaAccountDao(entityManager);
account = new Account();
account2 = new Account();
}
#After
public void tearDown() throws Exception {
entityManager.close();
factory.close();
}
/*
Delete a account popularized via the init.script
*/
// TODO CREATE A TESTE THATS RUNS
#Test
public void deleteAccountTest() throws Exception {
Account account = entityManager.find(Account.class, 1);
entityManager.getTransaction().begin();
boolean result = jpaAccountDao.delete(account.getId());
entityManager.getTransaction().commit();
Account res = jpaAccountDao.findById(1);
assertEquals(res, account);
assertNull(result);
}
}
(Init.script)
INSERT INTO BOOK (id, title, price, description, number, instantiationDate) VALUES (1,'Mio min Mio', 100.0, 'Book about two brothers', '8-321389213', '2016-05-11 23:42:21');
INSERT INTO BOOK (id, title, price, description, number, instantiationDate ) VALUES (2, 'Franks dagbok', 10.0, 'About the war and Auchwitch', '13-321321321', '2016-11-05 20:00:00' );
INSERT INTO CUSTOMER (FK_CUSTOMER, firstName, lastName, email, phoneNumber, birth) VALUES (1, 'Kim', 'Pedersen','kim#yahoo.no','90045870', '1980-11-05');
INSERT INTO CUSTOMER (FK_CUSTOMER, firstName, lastName, email, phoneNumber, birth) VALUES (2, 'Silje', 'Kyrra','silje#yahoo.no','45236585', '1999-1-15');
INSERT INTO LOGIN (FK_LOGIN, username,password ) VALUES (1,'kimPedda', 'kimSimDimSum');
INSERT INTO LOGIN (FK_LOGIN, username,password ) VALUES (2,'Silkyra', 'SanriKorraDigo');
INSERT INTO ACCOUNT (id, FK_CUSTOMER, FK_LOGIN ) VALUES (1, 1, 1 );
INSERT INTO ACCOUNT (id, FK_CUSTOMER, FK_LOGIN ) VALUES (2, 2, 2 );
I just figure it out. It was an error with my testfile =)
I needed to change the method to get a instance, and delete with the method rather than through entityManager =)
Case solved
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