I'm trying to work with hibernate and I have a class question and a class answer, and there's One To One relation between them, the code is successfully running but the foreign key is null, I don't know why. Here's my code
package io.com.learnHibernate;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name="question")
public class Question {
#Id
private int questionId;
private String question;
#OneToOne(mappedBy = "question")
private Answer answer;
public Question() {
super();
}
public Question(int questionId, String question, io.com.learnHibernate.Answer answer) {
super();
this.questionId = questionId;
this.question = question;
answer = answer;
}
public Answer getAnswer() {
return answer;
}
public void setAnswer(Answer answer) {
answer = answer;
}
public int getQuestionId() {
return questionId;
}
public void setQuestionId(int questionId) {
this.questionId = questionId;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
}
package io.com.learnHibernate;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name="answer")
public class Answer {
#Id
private int aId;
private String answer;
#OneToOne
#JoinColumn
private Question question ;
public Answer() {
super();
}
public Answer(int aId, String answer) {
super();
this.aId = aId;
this.answer = answer;
}
public int getaId() {
return aId;
}
public void setaId(int aId) {
this.aId = aId;
}
public String getAnswer() {
return answer;
}
public void setAnswer(String answer) {
this.answer = answer;
}
}
my hibernate.cfg.xml 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.MySQL5InnoDBDialect</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:3306/aliens </property>
<property name = "hibernate.connection.username">root</property>
<property name = "hibernate.connection.password">root</property>
<property name = "hibernate.hbm2ddl.auto">create</property>
<property name = "show_sql">true</property>
<!-- List of XML mapping files -->
<mapping class= "io.com.learnHibernate.Question"/>
<mapping class= "io.com.learnHibernate.Answer"/>
</session-factory>
</hibernate-configuration>
and my main function
package io.com.learnHibernate;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.*;
import com.mysql.cj.xdevapi.SessionFactory;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
//configuration
Configuration conf=new Configuration();
conf.configure("Hibernate.cfg.xml");
org.hibernate.SessionFactory factory=conf.buildSessionFactory();
//creating answer
Answer a1=new Answer();
a1.setaId(180);
a1.setAnswer("my name is hafida");
//creating question
Question q1=new Question();
q1.setQuestionId(3);
q1.setQuestion("wht is your name?");
q1.setAnswer(a1);
//session
Session s=factory.openSession();
Transaction tx=s.beginTransaction();
//save
s.save(q1);
s.save(a1);
tx.commit();
// s.close();
// factory.close();
}
}
I expected to have the value of the foreign key inserted, but it's null
You need to specify cascade type in your entities mapping:
#Entity
#Table(name="answer")
public class Answer {
#Id
private int aId;
private String answer;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn
private Question question;
// ...
}
#Entity
#Table(name="question")
public class Question {
#Id
private int questionId;
private String question;
#OneToOne(mappedBy = "question", cascade = CascadeType.ALL)
private Answer answer;
// ...
}
As you use bidirectional #OneToOne, you should make both sides in-sync:
Answer a1 = new Answer();
a1.setaId(180);
a1.setAnswer("my name is hafida");
Question q1 = new Question();
q1.setQuestionId(3);
q1.setQuestion("wht is your name?");
// make both sides in-sync
a1.setQuestion(q1);
q1.setAnswer(a1);
Then you can save it in this way:
s.save(q1);
// you need not use s.save(a1);
// a1 will be saved due to propagation of the q1 entity's state
Related
After starting the program (launching TomCat) there are no tables created in the schema, but the table "player" has to be created automatically.
I checked hibernate config, but can't find where is the problem.
I've tried changing hbm2ddl.auto to hibernate.hbm2ddl.auto (also create, create-drop etc.) but it didn't help.
If there are any ideas, please let me know. Thanks.
Entity class:
package com.game.entity;
import javax.persistence.*;
import java.util.Date;
#Entity
#Table(schema = "rpg", name = "player")
public class Player {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#Column(name = "name", length = 12, nullable = false)
private String name;
#Column(name = "title", length = 30, nullable = false)
private String title;
#Column(name = "race", nullable = false)
#Enumerated(EnumType.ORDINAL)
private Race race;
#Column(name = "profession", nullable = false)
#Enumerated(EnumType.ORDINAL)
private Profession profession;
#Column(name = "birthday", nullable = false)
private Date birthday;
#Column(name = "banned", nullable = false)
private Boolean banned;
#Column(name = "level", nullable = false)
private Integer level;
public Player() {
}
public Player(Long id, String name, String title, Race race, Profession profession, Date birthday, Boolean banned, Integer level) {
this.id = id;
this.name = name;
this.title = title;
this.race = race;
this.profession = profession;
this.birthday = birthday;
this.banned = banned;
this.level = level;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Race getRace() {
return race;
}
public void setRace(Race race) {
this.race = race;
}
public Profession getProfession() {
return profession;
}
public void setProfession(Profession profession) {
this.profession = profession;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public Boolean getBanned() {
return banned;
}
public void setBanned(Boolean banned) {
this.banned = banned;
}
public Integer getLevel() {
return level;
}
public void setLevel(Integer level) {
this.level = level;
}
}
Repository class:
package com.game.repository;
import com.game.entity.Player;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.query.NativeQuery;
import org.springframework.stereotype.Repository;
import javax.annotation.PreDestroy;
import java.util.List;
import java.util.Optional;
#Repository(value = "db")
public class PlayerRepositoryDB implements IPlayerRepository {
private final SessionFactory sessionFactory;
public PlayerRepositoryDB() {
Configuration configuration = new Configuration().configure().addAnnotatedClass(Player.class);
StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
#Override
public List<Player> getAll(int pageNumber, int pageSize) {
try(Session session = sessionFactory.openSession()){
NativeQuery<Player> nativeQuery = session.createNativeQuery("SELECT * FROM rpg.player", Player.class);
nativeQuery.setFirstResult(pageNumber * pageSize);
nativeQuery.setMaxResults(pageSize);
return nativeQuery.list();
}
}
Hibernate configuration:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.url">jdbc:mysql://localhost:3306/rpg</property>
<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="connection.username">root</property>
<property name="connection.password">1234</property>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.MySQL8Dialect</property>
<property name="show_sql">true</property>
<property name="hibernate.current_session_context_class">thread</property>
</session-factory>
</hibernate-configuration>
Full project code with pom.xml is available by link:
https://github.com/gamlethot/project-hibernate-1
1-Hibernate does not recognize your repository. You should not mark repo classes as #Repository because they are not interfaces and in your example they are working like a service. So they can be #Service.
2-Do not implement IPlayerRepository. Mark it as #Repository and just autowire it to your service classes (or use constructor injection and just use like a variable)
Like:
#Service
public class PlayerRepositoryDB {
private IPlayerRepository playerRepository;
public PlayerRepositoryDB (IPlayerRepository playerRepository){ //CONSTRUCTOR
this.playerRepository = playerRepository;...
3- DB repository classes are implementing IPlayerRepository but it must be marked as #Repository and It should extend either CrudRepository or JpaRepository (which extends CrudRepository already).
Like:
#Repository
public interface IPlayerRepository extends JpaRepository<Player, Long> {
//Here are the methods;
}
Here, the Long is the type of primary key of Player class.
Hibernate XML:
<property name="hibernate.connection.CharSet">utf8mb4</property>
<property name="hibernate.connection.characterEncoding">UTF-8</property>
<property name="hibernate.connection.useUnicode">true</property>
Connection url:
db.url=jdbc:mysql://localhost:3306/db_name?useUnicode=true&character_set_server=utf8mb4
As a side note I would like to make one clarification that UTF-8 is the character encoding while utf8mb4 is a character set that MySQL supports. MySQL's utf8mb4 is a superset to MySQL's utf8.
Spring/Hibernate filter:
<form accept-charset="UTF-8">
Problem solved.
It was because of javax.persistence.; import instead of
jakarta.persistence. in entity class.
I've created 2 entity classes:
package entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "fr")
public class FR {
#Id
#Column(name = "id")
private String id;
#Column(name = "pid")
private String pId;
#Column(name = "pname")
private String pName;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getpId() {
return pId;
}
public void setpId(String pId) {
this.pId = pId;
}
public String getpName() {
return pName;
}
public void setpName(String pName) {
this.pName = pName;
}
}
and
package entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "ar")
public class AR {
#Id
#Column(name = "id")
private String id;
#Column(name = "value1")
private String value1;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getValue1() {
return value1;
}
public void setValue1(String value1) {
this.value1 = value1;
}
}
and I'm trying to join these tables to fetch the record.
Query qry = session.createQuery("from FR left join AR on FR.pId = AR.id where FR.id=123 or FR.pId=123");
but getting an exception:
org.hibernate.QueryException: Unable to resolve path [FR.id], unexpected token [FR] [from entities.FR left join AR on FR.pId = AR.id where FR.id=123 or FR.pId=123]
and when I'm removing FR from the query
Query qry = session.createQuery("from FR left join AR on FR.pId = AR.id where id=123 or pId=123");
getting another exception:
org.hibernate.hql.internal.ast.QuerySyntaxException: Path expected for join! [from entities.FR left join AR on FR.pId = AR.id where id=123 or pId=123]
I'm in a learning stage of Hibernate and don't know what to do now.
If you've any other info regarding Left Join or the other Joins then please share that too.
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.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/examples?zeroDateTimeBehavior=convertToNull</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">Root#123</property>
<property name="hibernate.show_sql">true</property>
<mapping class="entities.FR"/>
<mapping class="entities.AR"/>
</session-factory>
</hibernate-configuration>
Main Class
package hibernate.joins;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
public class HibernateJoins {
public static void main(String[] args) {
SessionFactory sessionFactory = getSessionFactory();
Session session = sessionFactory.openSession();
Query qry = session.createQuery("from FR left join AR on FR.pId = AR.id and ( FR.id=123 or FR.pId=123 )");
List list = qry.list();
list.forEach(System.out::println);
session.close();
sessionFactory.close();
}
public static SessionFactory getSessionFactory () {
SessionFactory sessionFactory = new Configuration().configure("configurations/hibernate.cfg.xml").buildSessionFactory();
return sessionFactory;
}
}
Since you are using ON clause in your query, therefore, you can not to use where clause separately. Just keep on adding the condition using AND or OR clause(whichever is applicable)
I am learning manytomany relationship in hibernate from the tutorial. My example project has two tables called product_table and order_table. I was using many to many relationship between these two tables.
While executing my code I found the following error in the console:
Exception in thread "main" org.hibernate.MappingException: Could not determine type for: java.util.Collection, at table: product_details, for columns: [org.hibernate.mapping.Column(orders)]
at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:456)
at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:423)
at org.hibernate.mapping.Property.isValid(Property.java:226)
at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:597)
at org.hibernate.mapping.RootClass.validate(RootClass.java:265)
at org.hibernate.boot.internal.MetadataImpl.validate(MetadataImpl.java:329)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:459)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:710)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:726)
at com.hibernatetest.main.MainApp.hibernateSession(MainApp.java:98)
at com.hibernatetest.main.MainApp.main(MainApp.java:93)
Here's my Hibernate configuration file:
<!-- ~ Hibernate, Relational Persistence for Idiomatic Java ~ ~ License:
GNU Lesser General Public License (LGPL), version 2.1 or later. ~ See the
lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. -->
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- In case of using MySQL greater than 5 use MYSQL5 Dialect in stead of mysqldialect -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</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/hibernate_test?createDatabaseIfNotExist=true</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<mapping class="com.hibernatetest.dto.ProductDetails" />
<mapping class="com.hibernatetest.dto.OrderDetails" />
</session-factory>
</hibernate-configuration>
Here's my OrderDetails classes:
package com.hibernatetest.dto;
import java.util.ArrayList;
import java.util.Collection;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
#Entity
#Table(name = "product_details")
public class ProductDetails {
private int productId;
private String productName;
#ManyToMany(mappedBy="product_details")
private Collection<OrderDetails> orders=new ArrayList();
public ProductDetails() {
}
public ProductDetails(String productName) {
this.productName = productName;
}
#Id
#Column(name = "product_id")
#GeneratedValue(strategy = GenerationType.AUTO)
public int getProductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
#Column(name = "product_name")
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public Collection<OrderDetails> getOrders() {
return orders;
}
public void setOrders(Collection<OrderDetails> orders) {
this.orders = orders;
}
}
Here is my OrderDetails class:
package com.hibernatetest.dto;
import java.util.ArrayList;
import java.util.Collection;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name = "order_details")
public class OrderDetails {
private int orderId;
private String orderName;
#ManyToMany
private Collection<ProductDetails> products = new ArrayList();
public OrderDetails() {
super();
}
public OrderDetails(String orderName) {
super();
this.orderName = orderName;
}
#Id
#Column(name = "order_id")
#GeneratedValue(strategy = GenerationType.AUTO)
public int getOrderId() {
return orderId;
}
public void setOrderId(int orderId) {
this.orderId = orderId;
}
#Column(name = "order_name")
public String getOrderName() {
return orderName;
}
public void setOrderName(String orderName) {
this.orderName = orderName;
}
public Collection<ProductDetails> getProduct() {
return products;
}
public void setProduct(Collection<ProductDetails> products) {
this.products = products;
}
}
Here is MainApp class:
package com.hibernatetest.main;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.hibernatetest.dto.Address;
import com.hibernatetest.dto.Office;
import com.hibernatetest.dto.OrderDetails;
import com.hibernatetest.dto.ProductDetails;
import com.hibernatetest.dto.UserDetails;
public class MainApp {
public static void main(String[] args) {
/*
* UserDetails user = new UserDetails(); UserDetails user2=new UserDetails();
* Address address1=new Address("test street1", "test city1", "test state",
* "0000"); Address address2=new Address("test street2", "test city2",
* "test state", "0001"); //user.setUserId(2); user.setUsername("Test User 1");
* user2.setUsername("Test User 2"); user.setJoinedDate(new Date());
* user2.setJoinedDate(new Date()); user.setHomeAddress(address1);
* user.setOfficeAddress(address2); user2.setHomeAddress(address2);
* user2.setOfficeAddress(address1); user.setDescription("test data 1");
* user2.setDescription("test data 2"); user.setJoinedTime(new Date());
* user2.setJoinedTime(new Date());
*
* String officePhone1="00000000"; String officePhone2="00000001"; String
* officePhone3="00000002"; Collection<String> phoneNumbers=new
* ArrayList<String>(); phoneNumbers.add(officePhone1);
* phoneNumbers.add(officePhone2); phoneNumbers.add(officePhone3); Office
* office=new Office(1,"Test Office 1", address1,phoneNumbers);
*
* SessionFactory sessionFactory = new
* Configuration().configure().buildSessionFactory();
*
* Session session = sessionFactory.openSession();
*
* session.beginTransaction();
*
* session.save(user); session.save(user2); session.save(office);
*
* session.getTransaction().commit();
*
* session.close();
*
* user=null;
*
* session= sessionFactory.openSession(); session.beginTransaction();
* user=session.get(UserDetails.class,2);
*
* System.out.println(user.getUserId()+" "+user.getDescription());
*
* session.close(); office=null; session=sessionFactory.openSession();
* session.beginTransaction(); office=session.get(Office.class, 1);
* System.out.println(office.getOfficeName()); session.close();
* System.out.println(office.getPhoneList().size());
*/
ProductDetails product1 = new ProductDetails("Sample product 1");
ProductDetails product2 = new ProductDetails("Sample product 2");
ProductDetails product3 = new ProductDetails("Sample product 3");
ProductDetails product4 = new ProductDetails("Sample product 4");
OrderDetails order1 = new OrderDetails("Order No 1");
OrderDetails order2 = new OrderDetails("Order No 2");
product1.getOrders().add(order1);
product1.getOrders().add(order2);
product2.getOrders().add(order2);
order1.getProduct().add(product1);
order1.getProduct().add(product2);
order1.getProduct().add(product3);
order2.getProduct().add(product1);
order2.getProduct().add(product3);
order2.getProduct().add(product4);
List<Object> insetableObjects = new ArrayList<Object>();
insetableObjects.add(product1);
insetableObjects.add(product2);
insetableObjects.add(product3);
insetableObjects.add(product4);
insetableObjects.add(order1);
insetableObjects.add(order2);
hibernateSession(insetableObjects);
}
public static void hibernateSession(List<Object> collection) {
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
for (Object obj : collection) {
session.save(obj);
System.out.println("Object Added");
}
session.getTransaction().commit();
session.close();
}
}
Please guide me to the next steps and thanks in advance.
See this tutorial and Jack Flamp's comments. In order to establish a ManyToMany relationship, you need a #JoinTable referencing the table you want to use in its specific class, and a reference in the other. For instance, in your case it would be something like:
ProductDetails:
#Entity
#Table(name = "product_details")
public class ProductDetails {
private int productId;
private String productName;
#ManyToMany(cascade = { CascadeType.ALL })
#JoinTable(
name = "order_product",
joinColumns = { #JoinColumn(name = "productId") },
inverseJoinColumns = { #JoinColumn(name = "orderId") }
)
private Collection<OrderDetails> orders = new ArrayList();
[...]
OrderDetails:
#Entity
#Table(name = "order_details")
public class OrderDetails {
private int orderId;
private String orderName;
#ManyToMany(mappedBy = "orders")
private Collection<ProductDetails> products = new ArrayList();
Here, your "owning side" (= the one holding the information) is the product. Your product can have multiple orders, and an order belongs to multiple products. Of course, feel free to revert them as you wish if it does not suit your needs. The link I gave you explains well what each annotation does.
EDIT: Make sure that (in the example) the order_product table actually exists. Otherwise, it won't work.
I want to establish one to many relation between table vendor detail and product detail. like one vendor can have multiple products. but when i am inserting data into table its inserting all the four fields but not mapping vendorid into ProductDetail Table
and query generated is this.
Hibernate: insert into ProductInfo (productCategory, productDetails, productPrice, VendorId) values (?, ?, ?, ?) It shuld map vendor ID also but in table its empty.
VendorDetail.java
package com.cts.entity;
import javax.persistence.*;
#Entity
#Table(name = "VendorInfo")
public class VendorDetails {
#Id
#Column
private Long VendorId;
#OneToMany
private ProductDetails productdetail;
#Column
private String VendorName;
#Column
private String Password;
public String getVendorName() {
return VendorName;
}
public void setVendorName(String vendorName) {
VendorName = vendorName;
}
public Long getVendorId() {
return VendorId;
}
public void setVendorId(Long vendorId) {
VendorId = vendorId;
}
public String getPassword() {
return Password;
}
public void setPassword(String password) {
Password = password;
}
}
ProductDetails.java
package com.cts.entity;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity#Table(name = "ProductInfo")
public class ProductDetails {
#ManyToOne(cascade = CascadeType.ALL)#JoinColumn(name = "VendorId")
private VendorDetails vendordetails;
public ProductDetails() {
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column
private int productId;
#Column
private String productCategory;
#Column
private String productDetails;
#Column
private String productPrice;
public VendorDetails getVendordetails() {
return vendordetails;
}
public void setVendordetails(VendorDetails vendordetails) {
this.vendordetails = vendordetails;
}
public int getProductId() {
return productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public String getProductCategory() {
return productCategory;
}
public void setProductCategory(String productCategory) {
this.productCategory = productCategory;
}
public String getProductDetails() {
return productDetails;
}
public void setProductDetails(String productDetails) {
this.productDetails = productDetails;
}
public String getProductPrice() {
return productPrice;
}
public void setProductPrice(String productPrice) {
this.productPrice = productPrice;
}
}
DAO class ProductDetailDaoImpl.java
package com.cts.Dao;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.cts.entity.ProductDetails;
import com.cts.entity.to.ProductDetailsTo;
#Repository
public class ProductDetailDaoImpl implements ProductDetailDao {
#Autowired
SessionFactory sessionFactory;
#Transactional
public boolean saveProductInfo(ProductDetailsTo productTo) {
System.out.println("M in Registration DAO");
System.out.println(productTo.getProductCategory());
System.out.println(productTo.getProductDetails());
System.out.println(productTo.getProductId());
System.out.println(productTo.getProductPrice());
//getting productTo data to entity class
ProductDetails prodet = productTo.getEntity();
System.out.println("Value of product details is:" + prodet.getProductDetails());
sessionFactory.getCurrentSession().save(prodet);
return false;
}
}
VendorDetails has many ProductDetails so you need to make one to many annotation like this:-
#OneToMany(mappedBy="vendordetails") //mappedBy value will be what you declared //in ProductDetails class.
private Collection<ProductDetails> productdetail=new ArrayList<ProductDetails>;
and create the setter and getter of this.
Now in ProductDetails class you need to annotate many to one like this:-
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "VendorId")
private VendorDetails vendordetails;
Then a new column named 'VendorId' will be create in table 'ProductInfo' and since declare mappedBy value="vendordetails" so each vendor id would be insert.
I think you should replace the code
#OneToMany
private ProductDetails productdetail;
to
#OneToMany
private Set productdetailSet;
And create setter and getter for this.
You can visit the blog http://gaurav1216.blogspot.in/2014/01/hibernate-tutorial-day-5.html for one to many using annotation.
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.