How to properly use JPA/Hibernate? - java

I'm trying to understand annotations better with JPA / Hibernate and SQL Server.
I created a simple project: an abstract class named "Articles". Two classes inherit it: Ramette which adds a weight and Pen which adds a color. The code below is not working and I am unable to correct the errors. Do you have an idea? Thank you!
package fr.eni.hibernate.entities;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;
#Entity
#Table(name = "Articles")
#Inheritance( strategy = InheritanceType.SINGLE_TABLE )
#DiscriminatorColumn( name="type", discriminatorType = DiscriminatorType.STRING)
public abstract class Articles implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "idarticle")
private Integer idarticle;
#Column(name = "reference")
private String reference;
#Column(name = "marque")
private String marque ;
#Column(name = "designation")
private String designation;
#Column(name = "prixUnitaire")
private float prixUnitaire ;
#Column(name = "qteStock")
private int qteStock ;
public Articles() {
}
public Integer getIdArticle() {
return idarticle;
}
public String getReference() {
return reference;
}
public void setReference(String reference) {
this.reference = reference;
}
public String getMarque() {
return marque;
}
public void setMarque(String marque) {
this.marque = marque;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public float getPrixUnitaire() {
return prixUnitaire;
}
public void setPrixUnitaire(float prixUnitaire) {
this.prixUnitaire = prixUnitaire;
}
public int getQteStock() {
return qteStock;
}
public void setQteStock(int qteStock) {
this.qteStock = qteStock;
}
#Override
public String toString() {
return "Article [idArticle=" + idarticle + ", reference=" + reference + ", marque=" + marque + ", designation="
+ designation + ", prixUnitaire=" + prixUnitaire + ", qteStock=" + qteStock + "]";
}
}
package fr.eni.hibernate.entities;
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
#Entity
#DiscriminatorValue("Ramette")
public class Ramette extends Articles {
private static final long serialVersionUID = 1L;
private int grammage;
public Ramette() {
}
#Column(name = "grammage")
public int getGrammage() {
return grammage;
}
public void setGrammage(int grammage) {
this.grammage = grammage;
}
#Override
public String toString() {
return super.toString() + " Ramette [grammage=" + grammage + "]";
}
}
package fr.eni.hibernate.entities;
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
#Entity
#DiscriminatorValue("Stylo")
public class Stylo extends Articles {
private static final long serialVersionUID = 1L;
private String couleur;
public Stylo() {
}
#Column(name = "couleur")
public String getCouleur() {
return couleur;
}
public void setCouleur(String couleur) {
this.couleur = couleur;
}
#Override
public String toString() {
return super.toString() + " Stylo [couleur=" + couleur + "]";
}
}
package fr.eni.hibernate.entities;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;
public class Main {
public static void main(String[] args) throws Exception {
EntityManagerFactory entityManagerFactory = null;
EntityManager entityManager = null;
try {
entityManagerFactory = Persistence.createEntityManagerFactory("WebStore");
entityManager = entityManagerFactory.createEntityManager();
TypedQuery<Articles> query = entityManager.createQuery("from Articles", Articles.class);
List<Articles> art = query.getResultList();
for (Articles article : art) {
System.out.println(art.getClass().getName());
System.out.println("\t" + article);
}
} finally {
if (entityManager != null)
entityManager.close();
if (entityManagerFactory != null)
entityManagerFactory.close();
}
}
}
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns<img src="images/smilies/icon_mad.gif" border="0" alt="" title=":x" class="inlineimg" />si="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="WebStore">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>fr.eni.hibernate.entities.Articles</class>
<class>fr.eni.hibernate.entities.Stylo</class>
<class>fr.eni.hibernate.entities.Ramette</class>
<properties>
<property name="javax.persistence.jdbc.driver"
value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
<property name="javax.persistence.jdbc.url"
value="jdbc:sqlserver://localhost;database=PAPETERIE_TEST" />
<property name="javax.persistence.jdbc.user" value="xx" />
<property name="javax.persistence.jdbc.password" value="x" />
<property name="hibernate.dialect"
value="org.hibernate.dialect.SQLServerDialect" />
<property name="hibernate.format_sql" value="false" />
</properties>
</persistence-unit>
</persistence>
CREATE TABLE Articles
(
idarticle INT IDENTITY(1,1),
reference varchar(10) NOT NULL,
marque nvarchar(200) NOT NULL,
designation nvarchar(250) NOT NULL,
prixUnitaire float NOT NULL,
qteStock int NOT NULL,
grammage int NULL,
couleur nvarchar(50) NULL,
type nchar(10) NOT NULL,
CONSTRAINT PK_Articles PRIMARY KEY (idarticle)
)
INSERT INTO Articles (reference, marque, designation, prixUnitaire, qteStock, grammage, couleur, type)
VALUES ('Bic', 'BBOrange', 'Bic bille Orange', 1.2, 20, 0, 'Bleu', 'Stylo'),
('Bic', 'BBOrange', 'Bic bille Orange', 1.2, 20, 0,'noir', 'Stylo'),
('Clairef', 'CRA4S', 'Ramette A4 Sup', 9, 20, 80, null, 'Ramette');

This makes not much sense. This exception is only thrown when you have a discriminator in the table that has no match in the entity model. Maybe you have trailing spaces in the table?

Related

I am trying to map the entities using #OneToOne as a bidirectional mapping but getting weird exceptions

These are the exceptions I keep on getting repeatedly until I stop the server
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:755) ~[jackson-databind-2.11.3.jar:2.11.3]
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:178) ~[jackson-databind-2.11.3.jar:2.11.3]
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:728) ~[jackson-databind-2.11.3.jar:2.11.3]
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:755) ~[jackson-databind-2.11.3.jar:2.11.3]
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:178) ~[jackson-databind-2.11.3.jar:2.11.3]
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:728) ~[jackson-databind-2.11.3.jar:2.11.3]
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:755) ~[jackson-databind-2.11.3.jar:2.11.3]
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:178) ~[jackson-databind-2.11.3.jar:2.11.3]
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:728) ~[jackson-databind-2.11.3.jar:2.11.3]
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:755) ~[jackson-databind-2.11.3.jar:2.11.3]
Fields of Supplier and Catalog table
Catalog
-------
Sku Code(Unique)
Sku Name
Sku Description
Brand Name
Brand Description
Supplier Id(Foreign Key)
Supplier
--------
Supplier Id(Unique)
Supplier Name
Here is Catalog Entity(Catalog.java)
package com.inventory.entities;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.MapsId;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name = "catalog")
public class Catalog {
#Id
#Column(length = 50)
// #GeneratedValue
private int skuCode;
#Column(length = 50)
private String skuName;
#Column(length = 50)
private String skuDesc;
#Column(length = 50)
private String bName;
#Column(length = 50)
private String bDesc;
#OneToOne
#JoinColumn(name = "supplier_id")
private Supplier supplier;// FK
public Catalog() {
}
public Catalog(int skuCode, String skuName, String skuDesc, String bName, String bDesc, Supplier supplier) {
super();
this.skuCode = skuCode;
this.skuName = skuName;
this.skuDesc = skuDesc;
this.bName = bName;
this.bDesc = bDesc;
this.supplier = supplier;
}
public int getSkuCode() {
return skuCode;
}
public void setSkuCode(int skuCode) {
this.skuCode = skuCode;
}
public String getSkuName() {
return skuName;
}
public void setSkuName(String skuName) {
this.skuName = skuName;
}
public String getSkuDesc() {
return skuDesc;
}
public void setSkuDesc(String skuDesc) {
this.skuDesc = skuDesc;
}
public String getbName() {
return bName;
}
public void setbName(String bName) {
this.bName = bName;
}
public String getbDesc() {
return bDesc;
}
public void setbDesc(String bDesc) {
this.bDesc = bDesc;
}
public Supplier getSupplier() {
return supplier;
}
public void setSupplier(Supplier supplier) {
this.supplier = supplier;
}
#Override
public String toString() {
return "Catalog [skuCode=" + skuCode + ", skuName=" + skuName + ", skuDesc=" + skuDesc + ", bName=" + bName
+ ", bDesc=" + bDesc + ", supplier=" + supplier + "]";
}
}
Here is the Supplier Entity(Supplier.java)
package com.inventory.entities;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
#Entity
#Table(name = "supplier")
public class Supplier {
#Id
#Column(length = 50)
private int supplierId;
#Column(length = 50)
private String supplierName;
#OneToOne(mappedBy = "supplier",fetch = FetchType.LAZY)
private Catalog catalog;
public Supplier() {
}
public Supplier(int supplierId, String supplierName, Catalog catalog) {
super();
this.supplierId = supplierId;
this.supplierName = supplierName;
this.catalog = catalog;
}
public int getSupplierId() {
return supplierId;
}
public void setSupplierId(int supplierId) {
this.supplierId = supplierId;
}
public String getSupplierName() {
return supplierName;
}
public void setSupplierName(String supplierName) {
this.supplierName = supplierName;
}
public Catalog getCatalog() {
return catalog;
}
public void setCatalog(Catalog catalog) {
this.catalog = catalog;
}
#Override
public String toString() {
return "Supplier [supplierId=" + supplierId + ", supplierName=" + supplierName + ", catalog=" + catalog + "]";
}
}
Now my Requirement is that I want to get the Catalog obj using supplierId which is a Foreign key in Catalog Entity and to use the only #OneToOne as every catalog must have one unique supplier
package com.inventory.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import com.inventory.entities.Catalog;
import com.inventory.entities.Supplier;
import com.inventory.service.SupplierService;
#RestController
public class SupplierControllerImpl {
#Autowired
private SupplierService supplierService;
#GetMapping("/supplier1/{supplier_id}")
public Catalog getCatalog(#PathVariable int supplier_id) {
Supplier supplier = supplierService.getSupplierById(supplier_id);
return supplier.getCatalog();
}
}
SupplierService.java
package com.inventory.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.inventory.entities.Supplier;
import com.inventory.repository.SupplierRepository;
#Service
public class SupplierService {
#Autowired
private SupplierRepository supplierRepository;
public Supplier getSupplierById(int id) {
return supplierRepository.findById(id).get();
}
public Supplier insertSupplier(Supplier supplier) {
return supplierRepository.save(supplier);
}
}
Please help me as I am new to Spring and Hibernate as well in stackoverflow if anything needs to be edited or question is not clear please guide me so I can improve it further.
Thank you for viewing this question now finally I got the answer since I don't know the name of Problem that's why I face this difficult to find the answer. The problem that I was facing is Infinite JSON Recursion Problem, and the solution is to use #JsonManagedReference in the catalogue over supplierId and #JsonBackReference on Supplier over catalog.

cannot insert data to my table in database mysql

i have problem when insert to my database. here my setup for insert to my database.
First, I have method for getExecutionReport
first what i import
import com.dxtr.hibernate.DAOInsert;
import com.dxtr.hibernate.newOrderSingleEntity;
private void getExecutionReport(quickfix.Message message, String tipeMessage) {
// TODO Auto-generated method stub
try {
System.out.print("Message "+ message);
System.out.print("getExecutionReport "+tipeMessage);
newOrderSingleEntity newordersingleObj = new newOrderSingleEntity();
newordersingleObj.setSymbol(message.getString(Symbol.FIELD));
System.out.print(" symbol "+message.getString(Symbol.FIELD));
newordersingleObj.setMsgType(tipeMessage);
System.out.print(" tipeMessage "+tipeMessage);
newordersingleObj.setBodyLength(216);
System.out.print(" Body Length "+216);
newordersingleObj.setFixProtocol("FIX.4.2");
System.out.print("FixProtocol +FIX.4.2");
newordersingleObj.setTransactTime(message.getString(TransactTime.FIELD));
System.out.print(" time " +message.getString(TransactTime.FIELD));
newordersingleObj.setClOrdID(message.getString(ClOrdID.FIELD));
System.out.print(" ClOrdID "+message.getString(ClOrdID.FIELD));
newordersingleObj.setOrderID(message.getString(OrderID.FIELD));
System.out.print(" OrderID "+message.getString(OrderID.FIELD));
newordersingleObj.setExecID(message.getString(ExecID.FIELD));
System.out.print(" ExecID "+message.getString(ExecID.FIELD));
newordersingleObj.setExecTransType(message.getString(ExecTransType.FIELD));
System.out.print(" ExecTransType "+message.getString(ExecTransType.FIELD));
newordersingleObj.setOrdType(message.getString(OrdType.FIELD));
System.out.print(" OrdType "+message.getString(OrdType.FIELD));
newordersingleObj.setExecType(message.getString(ExecType.FIELD));
System.out.print(" ExecType "+message.getString(ExecType.FIELD));
newordersingleObj.setOrdStatus(message.getString(OrdStatus.FIELD));
System.out.print(" OrdStatus "+message.getString(OrdStatus.FIELD));
newordersingleObj.setSide(message.getInt(Side.FIELD));
System.out.print(" Side "+message.getInt(Side.FIELD));
newordersingleObj.setOrderQty(message.getDouble(OrderQty.FIELD));
System.out.print(" OrderQty "+message.getDouble(OrderQty.FIELD));
newordersingleObj.setLeavesQty(message.getDouble(LeavesQty.FIELD));
System.out.print(" LeavesQty "+message.getDouble(LeavesQty.FIELD));
newordersingleObj.setCumQty(message.getDouble(CumQty.FIELD));
System.out.print(" CumQty "+message.getDouble(CumQty.FIELD));
newordersingleObj.setLastShares(message.getInt(LastShares.FIELD));
System.out.print(" LastQty "+message.getInt(LastShares.FIELD));
System.out.print("sebelum insert ke db");
DAOInsert.newOrderSingleInsert(newordersingleObj);
} catch (FieldNotFound e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this code ok. but when i want to insert to my database my data cannot insert it.
here my entity
package com.dxtr.hibernate;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="New_Single_Order_Response",schema="dxtr_trades")
public class newOrderSingleEntity implements Serializable{
private static final long serialVersionUID = -1234424538928L;
#Id
#Column(name="response_id")
#GeneratedValue(strategy=GenerationType.AUTO)
private Integer id;
#Column(name="Fix_Protocol")
private String FixProtocol;
#Column(name="BodyLength")
private Integer BodyLength;
#Column(name="MsgSeqNum")
private Integer MsgSeqNum;
#Column(name="MsgType")
private String MsgType;
#Column(name="SenderCompId")
private String SenderCompId;
#Column(name="SendingTime")
private String SendingTime;
#Column(name="TargetCompID")
private String TargetCompID;
#Column(name="AveragePrice")
private Double AveragePrice;
#Column(name="ClOrdID")
private String ClOrdID;
#Column(name="CumQty")
private double CumQty;
#Column(name="Currency")
private String Currency;
#Column(name="ExecID")
private String ExecID;
#Column(name="LastShares")
private double LastShares;
#Column(name="OrderQty")
private Double OrderQty;
#Column(name="OrdStatus")
private String OrdStatus;
#Column(name="OrdType")
private String OrdType;
#Column(name="Side")
private Integer Side;
#Column(name="Symbol")
private String Symbol;
#Column(name="TransactTime")
private String TransactTime;
#Column(name="ExecType")
private String ExecType;
#Column(name="LeavesQty")
private double LeavesQty;
#Column(name="CheckSum")
private Integer CheckSum;
#Column(name="ExecTransType")
private String ExecTransType;
#Column(name="OrderID")
private String OrderID;
public Integer getResponse_ID() {
return this.id;
}
public void setResponse_ID(Integer id) {
this.id = id;
}
public String getFixProtocol() {
return this.FixProtocol;
}
public void setFixProtocol(String FixProtocol) {
this.FixProtocol = FixProtocol;
}
public Integer getBodyLength() {
return this.BodyLength;
}
public void setBodyLength(Integer BodyLength) {
this.BodyLength = BodyLength;
}
public Integer getMsgSeqNum() {
return this.MsgSeqNum;
}
public void setMsgSeqNum(Integer MsgSeqNum) {
this.MsgSeqNum = MsgSeqNum;
}
public String getMsgType() {
return this.MsgType;
}
public void setMsgType(String MsgType) {
this.MsgType = MsgType;
}
public String getSenderCompId() {
return this.SenderCompId;
}
public void setSenderCompId(String SenderCompId) {
this.SenderCompId = SenderCompId;
}
public String getSendingTime() {
return this.SendingTime;
}
public void setBodyLength(String SendingTime) {
this.SendingTime = SendingTime;
}
public String getTargetCompID() {
return this.TargetCompID;
}
public void setTargetCompID(String TargetCompID) {
this.TargetCompID = TargetCompID;
}
public Double getAveragePrice() {
return this.AveragePrice;
}
public void setAveragePrice(Double AveragePrice) {
this.AveragePrice = AveragePrice;
}
public String getClOrdID() {
return this.ClOrdID;
}
public void setClOrdID(String ClOrdID) {
this.ClOrdID = ClOrdID;
}
public double getCumQty() {
return this.CumQty;
}
public void setCumQty(double CumQty) {
this.CumQty = CumQty;
}
public String getCurrency() {
return this.Currency;
}
public void setCurrency(String Currency) {
this.Currency = Currency;
}
public String getExecID() {
return this.ExecID;
}
public void setExecID(String ExecID) {
this.ExecID = ExecID;
}
public double getLastShares() {
return this.LastShares;
}
public void setLastShares(double LastShares) {
this.LastShares = LastShares;
}
public Double getOrderQty() {
return this.OrderQty;
}
public void setOrderQty(Double OrderQty) {
this.OrderQty = OrderQty;
}
public String getExecType() {
return this.ExecType;
}
public void setExecType(String ExecType) {
this.ExecType = ExecType;
}
public String getOrdStatus() {
return this.OrdStatus;
}
public void setOrdStatus(String OrdStatus) {
this.OrdStatus = OrdStatus;
}
public String getOrdType() {
return this.OrdType;
}
public void setOrdType(String OrdType) {
this.OrdType = OrdType;
}
public Integer getSide() {
return this.Side;
}
public void setSide(Integer Side) {
this.Side = Side;
}
public String getSymbol() {
return this.Symbol;
}
public void setSymbol(String Symbol) {
this.Symbol = Symbol;
}
public String getTransactTime() {
return this.TransactTime;
}
public void setTransactTime(String TransactTime) {
this.TransactTime = TransactTime;
}
public double getLeavesQty() {
return this.LeavesQty;
}
public void setLeavesQty(double LeavesQty) {
this.LeavesQty = LeavesQty;
}
public Integer getCheckSum() {
return this.CheckSum;
}
public void setCheckSum(Integer CheckSum) {
this.CheckSum = CheckSum;
}
public String getExecTransType() {
return this.ExecTransType;
}
public void setExecTransType(String ExecTransType) {
this.ExecTransType = ExecTransType;
}
public String getOrderID() {
return this.OrderID;
}
public void setOrderID(String OrderID) {
this.OrderID = OrderID;
}
public String toString() {
return "OrderDetail?= Id: " + this.id + ", ClOrdID: " + this.ClOrdID + ", ExecID No.: " + this.ExecID + ", Symbol: " + this.Symbol;
}
}
and here my class for insert to database
package com.dxtr.hibernate;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import quickfix.StringField;
public class DAOInsert {
private DAOInsert dAOInsert;
static Session sessionObj;
static SessionFactory sessionFactoryObj;
public final static Logger logger = Logger.getLogger(DAOInsert.class);
// This Method Is Used To Create The Hibernate's SessionFactory Object
public static SessionFactory buildSessionFactory() {
// Creating Configuration Instance & Passing Hibernate Configuration File
Configuration configObj = new Configuration();
configObj.configure("hibernate.cfg.xml");
// Since Hibernate Version 4.x, ServiceRegistry Is Being Used
ServiceRegistry serviceRegistryObj = new StandardServiceRegistryBuilder().applySettings(configObj.getProperties()).build();
// Creating Hibernate SessionFactory Instance
sessionFactoryObj = configObj.buildSessionFactory(serviceRegistryObj);
return sessionFactoryObj;
}
public static void newOrderSingleInsert(newOrderSingleEntity newordersingleObj){
int count = 0;
try {
System.out.print("sudah di DAOInsert");
// Getting Session Object From SessionFactory
sessionObj = buildSessionFactory().openSession();
// Getting Transaction Object From Session Object
sessionObj.beginTransaction();
sessionObj.persist(newordersingleObj);
System.out.print(sessionObj.contains(newordersingleObj));
// Creating Transaction Entities
// newordersingleObj = new NewOrderSingle();
//newordersingleObj.setFixProtocol("FIX.4.2");
//newordersingleObj.setBodyLength(250);
//sessionObj.save(newordersingleObj);
//Committing The Transactions To The Database
sessionObj.getTransaction().commit();
//logger.info("\nSuccessfully Created '" + count + "' Records In The Database!\n");
} catch(Exception e) {
if(null != sessionObj.getTransaction()) {
logger.info("\n.......Transaction Is Being Rolled Back.......\n");
sessionObj.getTransaction().rollback();
}
e.printStackTrace();
} finally {
if(sessionObj != null) {
sessionObj.close();
}
}
}
}
i have also set persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="FastMatch" transaction-type="RESOURCE_LOCAL">
<class>com.dxtr.hibernate.newOrderSingleEntity</class>
<properties>
<property name="eclipselink.logging.level" value="INFO"/>
<property name="eclipselink.logging.level.sql" value="FINE"/>
<property name="eclipselink.logging.parameters" value="true"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://trades/tradesnew />
<property name="javax.persistence.jdbc.user" value="user" />
<property name="javax.persistence.jdbc.password" value="password" />
<property name="hibernate.show_sql" value="false" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
<property name="eclipselink.logging.level.connection" value="FINEST"/>
</properties>
</persistence-unit>
</persistence>
and also i have hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://url/trades</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.connection.username">user</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<mapping class="com.dxtr.hibernate.newOrderSingleEntity"></mapping>
</session-factory>
</hibernate-configuration>
but when i want to insert to my database this data cannot insert it.. but i don't know where is the error... i have catch the error using
catch(Exception e) {
if(null != sessionObj.getTransaction()) {
logger.info("\n.......Transaction Is Being Rolled Back.......\n");
sessionObj.getTransaction().rollback();
}
e.printStackTrace();
} finally {
if(sessionObj != null) {
sessionObj.close();
}
but there is no error in my console print... so where is the problem from my code ?
for information i use mysql5.7 version and using aws
best regards,
Fuad
I would suggest you enable MySQL logs, then follow the instructions at https://dev.mysql.com/doc/refman/5.7/en/server-logs.html and be sure to flush the logs. The logs should be at /bar/log/MySQL

Problems with named queries in Java

I have a problem. I made a dynamic web project using JPA, named queries and a Web Servlet. Here is how the project is organized:
enter image description here
Here are the classes:
Auto.java:
package it.ecipar.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Auto {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String marca, modello;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getMarca() {
return marca;
}
public void setMarca(String marca) {
this.marca = marca;
}
public String getModello() {
return modello;
}
public void setModello(String modello) {
this.modello = modello;
}
}
Hobby.java:
package it.ecipar.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Hobby {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String nome;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
}
Luogo.java:
package it.ecipar.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Luogo {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String nome;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
}
Persona.java:
package it.ecipar.model;
import java.util.Date;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
#NamedQueries({
#NamedQuery(name="persona.lista", query="SELECT o from it.ecipar.model.Persona o ORDER by p.cognome, p.nome")
})
#Entity
public class Persona {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String nome, cognome;
private Date dataDiNascita;
#OneToMany
private List<Auto> auto;
#ManyToMany
private List<Hobby> hobby;
#ManyToOne
private Luogo luogoDiNascita;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCognome() {
return cognome;
}
public void setCognome(String cognome) {
this.cognome = cognome;
}
public List<Auto> getAuto() {
return auto;
}
public void setAuto(List<Auto> auto) {
this.auto = auto;
}
public List<Hobby> getHobby() {
return hobby;
}
public void setHobby(List<Hobby> hobby) {
this.hobby = hobby;
}
public Luogo getLuogoDiNascita() {
return luogoDiNascita;
}
public void setLuogoDiNascita(Luogo luogoDiNascita) {
this.luogoDiNascita = luogoDiNascita;
}
public Date getDataDiNascita() {
return dataDiNascita;
}
public void setDataDiNascita(Date dataDiNascita) {
this.dataDiNascita = dataDiNascita;
}
}
JPAUtil.java:
package it.ecipar.common;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
public class JPAUtil {
private static EntityManagerFactory emf;
private EntityManager em;
public JPAUtil() {
if (emf == null) {
emf = Persistence.createEntityManagerFactory("MyProject");
}
em = emf.createEntityManager();
}
public Object insert(Object o) {
em.getTransaction().begin();
em.persist(o);
em.getTransaction().commit();
return o;
}
public Object update(Object o) {
em.getTransaction().begin();
Object res = em.merge(o);
em.getTransaction().commit();
return res;
}
public void delete(Object o) {
em.getTransaction().begin();
em.remove(em.contains(o) ? o : em.merge(o));
em.getTransaction().commit();
}
public Object load(Class<?> c, Integer id) {
return em.find(c, id);
}
public List<?> runNamedQuery(String name, HashMap<String, Object> params) {
Query query = em.createNamedQuery(name);
if (params != null) {
Set<String> keys = params.keySet();
for (String k : keys) {
query.setParameter(k, params.get(k));
}
}
return query.getResultList();
}
public Query createQuery(String q) {
return em.createQuery(q);
}
public void close() {
em.close();
}
public void closeFactory() {
emf.close();
}
}
Demo.java:
package it.ecipar.common;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import it.ecipar.model.Auto;
import it.ecipar.model.Hobby;
import it.ecipar.model.Luogo;
import it.ecipar.model.Persona;
public class Demo {
public static void main(String[] args) {
JPAUtil u = new JPAUtil();
for(int i = 0; i < 10; i++) {
save(u, i, i + 1);
}
u.close();
u.closeFactory();
}
public static void save(JPAUtil u, int i, int numAuto) {
Luogo l = new Luogo();
l.setNome("nome luogo " + i);
u.insert(l);
List<Hobby> listaHobby = new ArrayList<>();
Hobby h = new Hobby();
h.setNome("nome hobby " + i);
u.insert(h);
listaHobby.add(h);
List<Auto> listaAuto = new ArrayList<>();
for (int j = i; j < i + numAuto; j++) {
Auto a = new Auto();
a.setMarca("marca " + j);
a.setModello("modello " + j);
u.insert(a);
listaAuto.add(a);
}
Calendar cal = GregorianCalendar.getInstance();
cal.add(Calendar.YEAR, -20 * i);
Persona p = new Persona();
p.setNome("nome " + i);
p.setCognome("cognome " + i);
p.setDataDiNascita(cal.getTime());
p.setHobby(listaHobby);
p.setLuogoDiNascita(l);
p.setAuto(listaAuto);
u.insert(p);
}
}
Here is the persistence.xml file:
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
<persistence-unit name="MyProject" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>it.ecipar.model.Auto</class>
<class>it.ecipar.model.Hobby</class>
<class>it.ecipar.model.Luogo</class>
<class>it.ecipar.model.Persona</class>
<properties>
<property name="hibernate.connection.driver_class" value="org.postgresql.Driver" />
<property name="hibernate.connection.url" value="jdbc:postgresql://localhost:5432/persone"/>
<property name="hibernate.connection.username" value="postgres" />
<property name="hibernate.connection.password" value="postgres" />
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
<property name="hibernate.show_sql" value="true" /> <!-- Show SQL in console -->
<property name="hibernate.format_sql" value="true" />
</properties>
</persistence-unit>
</persistence>
Here is the PersonaServlet.java:
package it.ecipar.web;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import flexjson.JSONSerializer;
import it.ecipar.common.JPAUtil;
import it.ecipar.model.Persona;
#SuppressWarnings("serial")
#WebServlet(urlPatterns = { "/persone" })
public class PersonaServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String id = req.getParameter("id");
String json = null;
if (id == null) {
System.out.println("Ciao");
#SuppressWarnings("unchecked")
List<Persona> list = (List<Persona>) new JPAUtil().runNamedQuery("personalista",null);
JSONSerializer js = new JSONSerializer();
json = js.include("auto").include("hobby").serialize(list);
} else {
Persona p = (Persona) new JPAUtil().load(Persona.class, Integer.valueOf(id));
JSONSerializer js = new JSONSerializer();
json = js.include("auto").include("hobby").serialize(p);
}
resp.setContentType("application/json");
PrintWriter w = resp.getWriter();
w.print(json);
w.flush();
}
}
When I run the program it give me the sequent error:
Exception in thread "main" javax.persistence.PersistenceException: Unable to build entity manager factory
at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:83)
at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:54)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:55)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39)
at it.ecipar.common.JPAUtil.<init>(JPAUtil.java:19)
at it.ecipar.common.Demo.main(Demo.java:16)
Caused by: org.hibernate.HibernateException: Errors in named queries: persona.lista
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:545)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1857)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:850)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:843)
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:398)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:842)
at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:75)
... 5 more
Could anyone help me please? Thanks.
Your query
#NamedQuery(name="persona.lista", query="SELECT o from it.ecipar.model.Persona o ORDER by p.cognome, p.nome")
has an error in it. You have Persona o but are then ordering by p.cognome.... You need to use the same table reference so:
#NamedQuery(name="persona.lista", query="SELECT o from it.ecipar.model.Persona o ORDER by o.cognome, o.nome")

One to many mapping with list result illegal Argument exception not a known entity

I am new to JPA. Need to insert data to two databases tables(two tables are different that means no foreign key relationship).I am using POSTMAN to send json data from URL as well as payload body section.
Two entity classes are shown below.
USERREDIRECT.JAVA`
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Cacheable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.QueryHint;
import javax.persistence.Table;
import org.codehaus.jackson.annotate.JsonProperty;
#Entity
#Cacheable(false)
#NamedQueries({
#NamedQuery(name = "getuserRedirectById", query = "SELECT a FROM userRedirect a WHERE a.redirectId=:redirectId", hints = #QueryHint(name = "eclipselink.refresh", value = "true"))
,
#NamedQuery(name = "getAlluserRedirect", query = "SELECT a FROM userRedirect a order by a.redirectId", hints = #QueryHint(name = "eclipselink.refresh", value = "true"))})
#Table(name = "userRedirect")
public class userRedirect {
#Id
#Column(name = "redirect_id")
#JsonProperty("redirect_id")
private String redirectId;
#Column(name = "loop_ind")
#JsonProperty("loop_ind")
private String loopInd;
#OneToMany(mappedBy = "userRedirectEntity", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<userRedirectRicTgrpDetails> userRedirectRicTgrpDetailsList;
public userRedirect() {
}
public String getLoopInd() {
return loopInd;
}
public void setLoopInd(String loopInd) {
this.loopInd = loopInd;
}
public List<userRedirectRicTgrpDetails> getuserRedirectRicTgrpDetailsList() {
return userRedirectRicTgrpDetailsList;
}
public void setuserRedirectRicTgrpDetailsList(List<userRedirectRicTgrpDetails> userRedirectRicTgrpDetailsList) {
this.userRedirectRicTgrpDetailsList = userRedirectRicTgrpDetailsList;
}
/**
* #return the redirectId
*/
public String getRedirectId() {
return redirectId;
}
/**
* #param redirectId the redirectId to set
*/
public void setRedirectId(String redirectId) {
this.redirectId = redirectId;
}
#Override
public String toString() {
return "userRedirect :: RedirectId: " + redirectId + ", LoopInd : "
+ loopInd + ", Ric_Tgrp Details : " + userRedirectRicTgrpDetailsList;
}
}
userRedirectRicTgrpDetails.java
import javax.persistence.Cacheable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.QueryHint;
import javax.persistence.Table;
import org.codehaus.jackson.annotate.JsonProperty;
#Entity
#Cacheable(false)
#NamedQueries({
#NamedQuery(name = "getuserRedirectDetailsById", query = "SELECT a FROM userRedirectRicTgrpDetails a WHERE a.userRedirectEntity.redirectId=:redirectId ORDER BY a.priority", hints = #QueryHint(name = "eclipselink.refresh", value = "true"))
,
#NamedQuery(name = "getAlluserRedirectDetails", query = "SELECT a FROM userRedirectRicTgrpDetails a ORDER BY a.priority", hints = #QueryHint(name = "eclipselink.refresh", value = "true"))})
#Table(name = "userRedirect_ric_tgrp_details")
public class userRedirectRicTgrpDetails {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "row_id")
private int id;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "redirect_id")
private userRedirect userRedirectEntity;
#Column(name = "ric")
#JsonProperty("ric")
private String ric;
#Column(name = "tgrp")
#JsonProperty("tgrp")
private String tgrp;
#Column(name = "priority")
#JsonProperty("priority")
private int priority;
public userRedirectRicTgrpDetails() {
}
public userRedirect getuserRedirect() {
return userRedirectEntity;
}
public void setuserRedirect(userRedirect userRedirect) {
this.userRedirectEntity = userRedirect;
}
/**
* #return the ric
*/
public String getRic() {
return ric;
}
/**
* #param ric the ric to set
*/
public void setRic(String ric) {
this.ric = ric;
}
/**
* #return the tgrp
*/
public String getTgrp() {
return tgrp;
}
/**
* #param tgrp the tgrp to set
*/
public void setTgrp(String tgrp) {
this.tgrp = tgrp;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getPriority() {
return priority;
}
public void setPriority(int priority) {
this.priority = priority;
}
#Override
public String toString() {
return "userRedirectRicTgrpDetails ::RowId : " + id + ", RedirectId : " + userRedirectEntity.getRedirectId() + ", Ric : " + ric + ", Tgrp : " + tgrp
+ ", Priority : " + priority;
}
}
Exception:
SEVERE: Unexpected error while creating new RedirectGroup Exception =
java.lang.IllegalArgumentException: Object: callRedirect :: RedirectId: 1000, Lo
opInd : ORIG, Ric_Tgrp Details : [callRedirectRicTgrpDetails ::RowId : 0, Redire
ctId : 1000, Ric : RICXXX3, Tgrp : TGRPXXXX3, Priority : 1] is not a known entit
y type.
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNewO
bjectForPersist(UnitOfWorkImpl.java:4184)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.persist(Entity
ManagerImpl.java:368)
Database schema:
CREATE TABLE IF NOT EXISTS `userRedirect` (
`redirect_id` varchar(20) NOT NULL,
`loop_ind` varchar(4) NOT NULL,
PRIMARY KEY (`redirect_id`)
);
CREATE TABLE IF NOT EXISTS `userRedirect_ric_tgrp_details` (
`row_id` int(4) AUTO_INCREMENT,
`redirect_id` varchar(20) NOT NULL,
`ric` varchar(20) NOT NULL,
`tgrp` varchar (20) NOT NULL,
`priority` int NOT NULL,
PRIMARY KEY (`row_id`)
);
JSON INPUT:
{
"loop_ind": "ORIG",
"callRedirectRicTgrpDetailsList": [{
"ric": "RICXXX3",
"tgrp": "TGRPXXXX3",
"priority": 1
}]
}
and redirect_id is given from URL
Persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
<persistence-unit name="TEST_CALLREDIRECT_PERSISTENCE" transaction-type="RESOURCE_LOCAL">
<class>com.mypackage.userRedirect</class>
<class>com.mypackage.userRedirectRicTgrpDetails</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://127.0.0.1:3306/CallRedirect" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="password" />
</properties>
</persistence-unit>
</persistence>
DAO.Class:
public userRedirect createNewuserRedirect(userRedirect userRedirect){
try {
System.out.println("inside dao.....");
LOGGER.fine("createNewRedirectGroup method invoked in dao with userRedirect : " + userRedirect);
entityManager.getTransaction().begin();
entityManager.persist(userRedirect);
entityManager.getTransaction().commit();
return userRedirect;
} catch (Exception e) {
System.out.println(e);
}
}

Hibernate annotations - date cannot be mapped

I've got a problem. I spend over one hour searching through the Internet but I did find nothing....
I have a simple Table class and one of its elements is List of java.util.Date. When I run the program, the exception is shown:
> org.hibernate.AnnotationException: Use of #OneToMany or #ManyToMany
> targeting an unmapped class:
> com.model.Time.timetable[java.util.Date].
My config file:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="hibernate.connection.driver_class">
com.mysql.jdbc.Driver
</property>
<!-- Assume test is the database name -->
<property name="hibernate.connection.url">
jdbc:mysql://localhost:3036/test
</property>
<property name="hibernate.connection.username">
root
</property>
<property name="hbm2ddl.auto">create</property>
<property name="hibernate.bytecode.use_reflection_optimizer">false</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<mapping class="com.model.Cinema" />
<mapping class="com.model.Time" />
</session-factory>
</hibernate-configuration>
and my class:
package com.model;
import static javax.persistence.GenerationType.IDENTITY;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import info.talacha.filmweb.models.Movie;
#Entity
#Table(name = "Time")
public class Time implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
private int id;
#OneToMany(cascade = CascadeType.ALL)
#JoinColumn(name = "time_id")
private List<Date> timetable;
#Column(name = "movie")
private Movie movie;
#Column(name = "dubbing")
private boolean dubbing;
#Column(name = "subtitles")
private boolean subtitles;
#Column(name = "threeDimensions")
private boolean threeDimensions;
public Time(){
timetable = new ArrayList<Date>();
dubbing= false;
subtitles = false;
threeDimensions = false;
movie = new Movie();
}
public Time(int id, List<Date> timetable, Movie movie, boolean dubbing, boolean subtitles, boolean is3dMovie) {
super();
this.id = id;
this.timetable = timetable;
this.movie = movie;
this.dubbing = dubbing;
this.subtitles = subtitles;
threeDimensions = is3dMovie;
}
public boolean isThreeDimensions() {
return threeDimensions;
}
public void setThreeDimensions(boolean threeDimensions) {
this.threeDimensions = threeDimensions;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Movie getMovie() {
return movie;
}
public void setMovie(Movie movie) {
this.movie = movie;
}
public Time(List<Date> timetable, Movie movie,boolean dubbing, boolean subtitles,boolean is3D) {
this.timetable = timetable;
this.dubbing = dubbing;
this.subtitles = subtitles;
this.movie = movie;
this.threeDimensions = is3D;
}
public List<Date> getTimetable() {
return timetable;
}
public void setTimetable(List<Date> timetable) {
this.timetable = timetable;
}
public boolean isDubbing() {
return dubbing;
}
public void setDubbing(boolean dubbing) {
this.dubbing = dubbing;
}
public boolean isSubtitles() {
return subtitles;
}
public void setSubtitles(boolean subtitles) {
this.subtitles = subtitles;
}
#Override
public String toString() {
return "Time [timetable=" + timetable + ", movie=" + movie + ", dubbing=" + dubbing + ", subtitles="
+ subtitles + ", is3DMovie=" + threeDimensions + "]";
}
}
This way of mapping (oneToMany) worked great when I used it for different type... I have no idea what's wrong. I tried few things but they didn't work. I will be grateful for your help!
OneToMany is used to create an association between two entities. java.util.Date is not an entity. It's a basic type. What you want is #ElementCollection.
Try usin #Temporal annotation like this:
#Temporal(value = TemporalType.TIMESTAMP)
#OneToMany(cascade = CascadeType.ALL)
#JoinColumn(name = "time_id")
private List<Date> timetable;
Try Date attribut from java.sql.Date to define each Date attributs of the Time class.
See you.

Categories

Resources