I have this simple bean name Brand.
I am able to create table out of him but i cant insert data (Mysql).
The error:
Exception in thread "main" org.hibernate.MappingException: Unknown entity: com.hibernate.beans.Brand
This is the Bean:
package com.hibernate.beans;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Brand {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long brandId;
private String name;
private String url;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Long getBrandId() {
return brandId;
}
public void setBrandId(Long brandId) {
this.brandId = brandId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
this is how i try to insert data (and where i get the error):
Brand brand = new Brand();
brand.setName("test");
brand.setUrl("http://www.google.com");
Session ses = new AnnotationConfiguration().configure().buildSessionFactory().getCurrentSession();
Transaction t = ses.beginTransaction();
ses.save(brand);
t.commit();
this is how the table is created successfully:
AnnotationConfiguration config = new AnnotationConfiguration();
config.addAnnotatedClass(Brand.class);
config.configure();
new SchemaExport(config).create(true, true);
The session factory you use to interact with the db needs to know about the entities.
In your case you need to change the code to add a Brand like this:
Brand brand = new Brand();
brand.setName("test");
brand.setUrl("http://www.google.com");
AnnotationConfiguration c = new AnnotationConfiguration();
c.addAnnotatedClass(Brand.class);
c.configure();
Session ses = c.buildSessionFactory().getCurrentSession();
Transaction t = ses.beginTransaction();
ses.save(brand);
t.commit();
Related
Following is my Person class:
package com.subir.sample;
import java.io.Serializable;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
#Entity
#Table(name ="person",uniqueConstraints = {#UniqueConstraint(columnNames= {"NAME"})})
public class Person implements Serializable{
/**
*
*/
private static final long serialVersionUID = -2728179031744032393L;
int age;
String name;
char isVip;
public Person() {
}
public Person(int age, String name, char isVip) {
this.age = age;
this.name = name;
this.isVip = isVip;
}
#Id
#Column(name="AGE")
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
#Id
#Column(name="NAME")
//#OneToMany(mappedBy="NAME")
private Set <Subject> subjects;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Id
#Column(name="ISVIP")
public char getIsVip() {
return isVip;
}
public void setIsVip(char isVip) {
this.isVip = isVip;
}
}
And the following is my class for add and view persons.
package com.subir.sample;
import org.hibernate.Transaction;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
public class PersonDbAccess {
public static void addPerson(String name, int age, char isVip, Session session, org.hibernate.Transaction tx) {
try {
tx = session.beginTransaction();
Person p = new Person(age, name, isVip);
session.save(p);
tx.commit();
} catch (Exception e) {
tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
public static void viewPerson(String name, Session session) {
try {
System.out.println("Name value in view method is :: " + name);
Person person = (Person)session.get(Person.class, name);
System.out.println("Person.class is ::" + Person.class + " Person.class.getName is :: "
+ Person.class.getName() + " Person.class.getSimpleName() is :: " + Person.class.getSimpleName()
+ " Person.class.getCanonicalName is :: " + Person.class.getCanonicalName());
} catch (Exception e) {
e.printStackTrace();
} finally {
session.close();
}
}
public static void main(String[] args) {
SessionFactory factory = HibernateUtils.buildSessionFactory();
Session session = factory.openSession();
Transaction tx = null;
String name = "Subir";
int age = 20;
char isVip = 'Y';
// addPerson(name,age,isVip,session,tx);
viewPerson("Subir", session);
}
}
And following is my stacktrace:
Exception in thread "main" org.hibernate.TypeMismatchException: Provided id of the wrong type for class com.subir.sample.Person. Expected: class com.subir.sample.Person, got class java.lang.String
at org.hibernate.event.internal.DefaultLoadEventListener.checkIdClass(DefaultLoadEventListener.java:166)
at org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:86)
at org.hibernate.internal.SessionImpl.fireLoad(SessionImpl.java:1240)
at org.hibernate.internal.SessionImpl.access$1900(SessionImpl.java:204)
at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.doLoad(SessionImpl.java:2842)
at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.load(SessionImpl.java:2816)
at org.hibernate.internal.SessionImpl.get(SessionImpl.java:1076)
at com.subir.sample.PersonDbAccess.main(PersonDbAccess.java:53)
Even though, I am passing object.class,String in the get method of the session object, it is giving me type mismatch exception.
You need to pass the ID to your hibernate session get method. In your case you have a compound key , fetching only by name might result in more than one object being returned which contradicts with the nature of the get operation which returns a single object by primary key.
You need to use a Criteria or Query here.
On another note if you want to use the Session.get method, instead of marking multiple columns with ID which is not JPA complient you should create an EmbededId and use it in the Session.get method. Then it will not incompatible type.
Read https://vladmihalcea.com/the-best-way-to-map-a-composite-primary-key-with-jpa-and-hibernate/
UPDATE:
I can see you have Unique constraint on name. Why do you need the AGE and the isVip to be part of your key , because marking them with ID you are effectivly making them part of your key.
I have a Student entity. My idea is to collect multiple student objects in an ArrayList and save all objects from that list to the database. When do you use #ElementCollection annotation? Does it apply to situations like this?
Student:
package basic;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Student {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
public Student() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return "Student [id=" + id + ", name=" + name + "]";
}
public Student(String name) {
this.name = name;
}
}
Runner:
package basic;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class Runner {
public static void main(String[] args) {
SessionFactory sessionFactory = new Configuration().configure("/basic/hibernate.cfg.xml").buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
List<Student> students = new ArrayList<>();
students.add(new Student("Michael"));
students.add(new Student("Dave"));
students.add(new Student("Tom"));
students.add(new Student("Dinesh"));
students.add(new Student("Lakshman"));
students.add(new Student("Cruise"));
session.save(students);
session.getTransaction().commit();
session.close();
}
}
Error
Exception in thread "main" org.hibernate.MappingException: Unknown entity: java.util.ArrayList
at org.hibernate.metamodel.internal.MetamodelImpl.entityPersister(MetamodelImpl.java:620)
at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1596)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:104)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:668)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:660)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:655)
at basic.Runner.main(Runner.java:27)
You have to do something like this:
for(Student student : students) {
session.save(student);
}
If you want to save entity you should map it. ArrayList<> is not mapped entity. Student has mapping so you should save it separately.
#ElementCollection you should use to define relation between object - here you have nice explenation https://en.wikibooks.org/wiki/Java_Persistence/ElementCollection
To save list of object, you need to iterate by objects, something like this -> How to insert multiple rows into database using hibernate?
I would further recommend to use another Hibernate command to avoid an Out Of Memory error...
SessionFactory sessionFactory = config.buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
for (int i = 0 ; i < students.size(); i++) {
session.save(students.get(i));
if (i % 100 == 0) {//a batch size for safety
session.flush();
session.clear();
}
}
transaction.commit();
session.close();
sessionFactory.close();
I am able to persist objects in relational database using hibernate.
please look at following code.
package one;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.SecondaryTable;
import javax.persistence.Table;
#Entity
public class Customer {
#Id
private int customerId;
private String customerName;
private String customerAddress;
private int creditScore;
private int rewardPoints;
public Customer()
{
}
public Customer(int customerId,String customerName,String customerAddress,int creditScore,int rewardsPoints)
{
this.customerId=customerId;
this.customerAddress=customerAddress;
this.creditScore=creditScore;
this.customerName=customerName;
this.rewardPoints=rewardsPoints;
}
public int getCustomerId() {
return customerId;
}
public void setCustomerId(int customerId) {
this.customerId = customerId;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getCustomerAddress() {
return customerAddress;
}
public void setCustomerAddress(String customerAddress) {
this.customerAddress = customerAddress;
}
public int getCreditScore() {
return creditScore;
}
public void setCreditScore(int creditScore) {
this.creditScore = creditScore;
}
public int getRewardPoints() {
return rewardPoints;
}
public void setRewardPoints(int rewardPoints) {
this.rewardPoints = rewardPoints;
}
}
Then to save object of this class i used following class. following class creates the object of class Customer and saves that object in database then again retrieves it and prints the CustomerName property of every saved object.
package one;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class TestCustomer {
public static void main(String args[])
{
Customer cust = new Customer(13,"Sara","Banglore",9000,60);
SessionFactory factory = new Configuration().configure().buildSessionFactory();
Session session = factory.openSession();
session.beginTransaction();
session.save(cust);
session.getTransaction().commit();
session.close();
session = factory.openSession();
session.beginTransaction();
List list = session.createQuery("FROM Customer").list();
Iterator iterator = list.iterator();
while(iterator.hasNext())
{
Customer custA = (Customer)iterator.next();
System.out.println("First Name\t"+custA.getCustomerName());
}
session.getTransaction().commit();
session.close();
}
}
I executed above code quite a number of times. code is running fine. it is able to fetch all objects which are saved.
but then i used oracle toad and fired a sql statement as
Insert into Customer(CUSTOMERID,CREDITSCORE,CUSTOMERNAME,REWARDPOINTS,CUSTOMERADDRESS)
VALUES(87,4000,'Saurabh',20,'Kalwa');
record gets stored in the table but when i execute above code, i am not able to fetch this record.
one conclusion i can draw is hibernate only returns persisted objects, but still is there any other way i can get all records ?
Are you sure you have submitted the record after inserting with toad for oracle?(you can open another client and execute a select to make sure it can be fetched from sql client).
If you want to debug, you can enable the sql logging function of hibernate, and then execute the sql which hibernate generates for your query in a sql client to make sure all the records can be fetched correctly.
And some suggestions for using JPA:
Make sure the #Entity has a name value which mapping to your physical table to avoid table mapping confusion.
Use #Column(name="column") for all your fields to mapping to the physical table column to avoid confusion.
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.
These are my pojo class
Orderdetail.java
package online.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name = "orderdetail")
public class OrderDetail {
#Id
#Column(name="order_detail_id")
private int order_detail_id;
#Column(name="bill")
private float bill;
#ManyToOne
#JoinColumn(name = "p_id" )
private Product p_id;
#ManyToOne
#JoinColumn(name = "o_id" )
private Order o_id;
public int getOrder_detail_id() {
return order_detail_id;
}
public void setOrder_detail_id(int order_detail_id) {
this.order_detail_id = order_detail_id;
}
public float getBill() {
return bill;
}
public void setBill(float bill) {
this.bill = bill;
}
public Product getP_id() {
return p_id;
}
public void setP_id(Product p_id) {
this.p_id = p_id;
}
public Order getO_id() {
return o_id;
}
public void setO_id(Order o_id) {
this.o_id = o_id;
}
}
My Order.java
package online.model;
import java.util.Date;
import java.util.List;
import java.util.Set;
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.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
#Entity
#Table(name = "ordertable")
public class Order {
#Id
#Column(name = "order_id")
private int order_id;
#OneToMany(mappedBy = "o_id",cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<OrderDetail> orderdetail;
#ManyToOne
#JoinColumn(name = "u_id")
private UserDetail u_id;
public UserDetail getU_id() {
return u_id;
}
public void setU_id(UserDetail u_id) {
this.u_id = u_id;
}
#Column(name = "date")
#Temporal(TemporalType.TIMESTAMP)
private Date date;
#Column(name = "totalbill")
private Float totalbill;
public Float getTotalbill() {
return totalbill;
}
public void setTotalbill(Float totalbill) {
this.totalbill = totalbill;
}
public List<OrderDetail> getOrderdetail() {
return orderdetail;
}
public void setOrderdetail(List<OrderDetail> orderdetail) {
this.orderdetail = orderdetail;
}
public int getOrder_id() {
return order_id;
}
public void setOrder_id(int order_id) {
this.order_id = order_id;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
When ever I am trying to save order class I want my orderdetail class also get saved but when I am trying to save the List in order,Is is not getting saved and there is not error provided by hibernate that can help...
Thanks for the help
when i am trying to to persist the order class
Hibernate: select orderdetai_.order_detail_id, orderdetai_.bill as bill7_, orderdetai_.o_id as o3_7_, orderdetai_.p_id as p4_7_ from orderdetail orderdetai_ where orderdetai_.order_detail_id=?
This what I am getting output.
This is my code which save the class
#Override
public boolean payment(String username, Integer ordernumber, Date date,
Float totalbill, List<Integer> list) {
Session session = sessionFactory.openSession();
Transaction tranction = session.beginTransaction();
try {
Query query = session
.createQuery("from UserDetail where user_username = :username");
query.setParameter("username", username);
List<UserDetail> userdetaillist = query.list();
UserDetail userdetail = userdetaillist.get(0);
query = session
.createQuery("from ProductDetail where product_detail_id in(:list)");
query.setParameterList("list", list);
List<ProductDetail> productdetail = query.list();
Order order = new Order();
order.setOrder_id(ordernumber);
order.setDate(date);
order.setU_id(userdetail);
order.setTotalbill(totalbill);
List<OrderDetail> orderdetail = new ArrayList<OrderDetail>();
OrderDetail ordetail = new OrderDetail();
for (ProductDetail pro : productdetail) {
ordetail.setO_id(order);
ordetail.setP_id(pro.getProduct_id());
ordetail.setBill(pro.getProduct_id().getProduct_sell_price());
orderdetail.add(ordetail);
}
System.out.print("totalbill" + totalbill);
System.out.println(orderdetail);
order.setOrderdetail(orderdetail);
session.save(order);
tranction.commit();
return true;
} catch (Exception e) {
tranction.rollback();
e.getStackTrace();
}
return false;
}
I think ordetail has to be created inside the for.. You are modifying the same object for each productdetail. Should be like this:
List<OrderDetail> orderdetail = new ArrayList<OrderDetail>();
OrderDetail ordetail = null;
for (ProductDetail pro : productdetail) {
ordetail = new OrderDetail();
ordetail.setO_id(order);
ordetail.setP_id(pro.getProduct_id());
ordetail.setBill(pro.getProduct_id().getProduct_sell_price());
orderdetail.add(ordetail);
}
Hey I have recheck my pojo class and I found out the mistake I have done. I have made change and it work properly now.
I was not setting the the id for Orderdetail table. It was auto increment in database.
So it was giving me error ""
So I have made change in orderdetail iD
"#GeneratedValue(strategy=GenerationType.AUTO)" So now It is working fine cause now hibernate know that the id will get value from database.
Thanks for the help and for your time