Hibernate MAPPING error with persistence class - java

Hello everyone I am making a web-app and having some problems. I am sharing my codes as well as problems.
and here is my dao
package service;
import java.util.List;
import com.blog.mapperclass.UserData;
public interface UserService {
public void addUser(UserData data);
//public List <UserData> getAllUsers();
}
this is my DAO implementation
package com.blog.dao;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean;
import org.springframework.stereotype.Component;
import com.blog.mapperclass.UserData;
import service.UserService;
#Component
public class Usersdao implements UserService{
SessionFactory session= new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
#Override
public void addUser(UserData data) {
Session ses=session.openSession();
ses.beginTransaction();
ses.save(data);
ses.getTransaction().commit();
System.out.println("user added");
}
}
my request mapping
#RequestMapping("/submit")
public String showSubmit(#ModelAttribute UserData data){
dao.addUser(data);
return "submit";
}
my cfg file
<?xml version="1.0" encoding="utf-8"?>
<!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>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:8086/blog</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="connection.pool_size">1</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">validate</property>
<mapping class="com.blog.mapperclass.UserData"></mapping>
</session-factory>
</hibernate-configuration>
and here is the error
Constructor threw exception; nested exception is org.hibernate.MappingException: An AnnotationConfiguration instance is required to use <mapping class="com.blog.mapperclass.UserData"/>
and when I use :
SessionFactory session= new AnnotationConfiguration().configure("hibernate.cfg.xml").buildSessionFactory();
it gives error
Failed to instantiate [com.blog.dao.Usersdao]: Constructor threw exception; nested exception is java.lang.IncompatibleClassChangeError: Implementing class
And all my jars are updated
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.6.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.5.5-Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.common</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>4.0.4.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.10.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-hibernate3</artifactId>
<version>2.0.8</version>
</dependency>
Please tell me the some solution for the problem I am newbie.
P.S : here is my pojo class
package com.blog.mapperclass;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import org.springframework.stereotype.Component;
#Entity
#Table(name="users")
#Component
public class UserData {
#Id
#Column
private String user_id;
#Column
private String name;
#Column
private String password;
#Column
private String email;
#Column
private String phone;
#Column
private int roll_id;
public UserData(String user_id, String name, String password, String email, String phone, int roll_id) {
super();
this.user_id = user_id;
this.name = name;
this.password = password;
this.email = email;
this.phone = phone;
this.roll_id = roll_id;
}
public UserData(){}
public UserData(String name, String password, String email, String phone) {
this.name = name;
this.password = password;
this.email = email;
this.phone = phone;
}
public UserData(String user_id, String name, String password, String email, String phone) {
super();
this.user_id = user_id;
this.name = name;
this.password = password;
this.email = email;
this.phone = phone;
}
public String getUser_id() {
return user_id;
}
public void setUser_id(String user_id) {
this.user_id = user_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
and my sql table :
click here for image

Related

Error : org.hibernate.MappingException: Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister

I am getting error when i run application.
This Is My Simple Hibernate Application.
When I Run My Application Is Eclipse IDE It Gives Me Error.
Error : org.hibernate.MappingException: Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister
I Get This Error When I Run My Application.
This Is My Student Class.
Student.java
package com.nikunj.hibernate.demo.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "student")
public class Student {
#Id
#Column(name = "id")
private int id;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#Column(name = "email")
private String email;
public Student() {
// super();
}
public Student(String firstName, String lastName, String email) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return "Student [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]";
}
}
This Is My Hibernate Configuration XML File.
hibernate.cfg.xml
<!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>
<!-- JDBC Database connection settings -->
<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hb_student_tracker?useSSL=false&serverTimezone=UTC</property>
<property name="connection.username">hbstudent</property>
<property name="connection.password">hbstudent</property>
<!-- JDBC connection pool settings ... using built-in test pool -->
<property name="connection.pool_size">1</property>
<!-- Select our SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Echo the SQL to stdout -->
<property name="show_sql">true</property>
<!-- Set the current session context -->
<property name="current_session_context_class">thread</property>
</session-factory>
</hibernate-configuration>
This Is My Main Class.
CreateStudentDemo.java
package com.nikunj.hibernate.demo;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.nikunj.hibernate.demo.entity.Student;
public class CreateStudentDemo {
public static void main(String[] args) {
try {
// Create session factory
SessionFactory factory = new Configuration().configure().addAnnotatedClass(Student.class)
.buildSessionFactory();
// Use the session object to save Java object
Session session = factory.getCurrentSession();
// Create a student object
System.out.println("Creating new student object...");
Student tempStudent = new Student("Nikunj", "Rathva", "Nikunjrathva108#gmail.com");
// Start a transaction
session.beginTransaction();
// Save the student object
System.out.println("Saving the student...");
session.save(tempStudent);
// Commit transaction
session.getTransaction().commit();
System.out.println("Done!");
factory.close();
} catch (Exception e) {
System.out.println("\n\n\nError : " + e + "\n\n\n");
e.printStackTrace();
}
}
}
```[Jar Files For Hibernate ORM][1]
[1]: https://i.stack.imgur.com/6iORy.png

Error: Exception in thread "main" org.hibernate.MappingException: Unknown entity: com.hibernate.demo.model.Contact

Before you mark it duplicate, Please read below :
I have already tried all the given answers in similar Questions-
My Import for #Entity is correct:import javax.persistence.Entity;
Mapping for entity in hibernate.cfg.xml is present
Class is mapped from pkg level:"com.hibernate.demo.model.Contact"
AnnotationConfiguration is also not resolving the issue.
All the other second to third best answers were tried too.
Background : I have created a Spring-boot project and I am trying to learn hibernate, I am using H2 db and I am facing >Unknown entity: com.hibernate.demo.model.Contact
I have verified that mapping of the class is present in
hibernate.cfg.xml
<mapping class="com.hibernate.demo.model.Contact"/>
I have also verified that mapping has full pkg level mapping path
This is the my hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!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>
<!-- Database connection settings -->
<property name="connection.driver_class">org.h2.Driver</property>
<property name="connection.url">jdbc:h2:./data/contactmgr</property>
<property name="connection.username">sa</property>
<property name="hibernate.default_schema">PUBLIC</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.H2Dialect</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
<property name="show_sql">true</property>
<mapping class="com.hibernate.demo.model.Contact"/>
</session-factory>
</hibernate-configuration>
my Application.java Main class :-
package com.hibernate.demo;
import java.io.IOException; import java.io.RandomAccessFile; import java.nio.channels.FileLock;
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 com.hibernate.demo.model.Contact;
public class Application {
//Session factory
private static final SessionFactory sessionFactory = buildSesssionFactory();
public static void main(String[] args) throws Exception {
System.out.println("Session factory");
Contact contact = new Contact.ContactBuilder("Bob", "Marley").withEmail("bob.nik#gmail.com").withPhone(5859789733L).build();
//Open a Session
System.out.println("Open a Session");
Session session = sessionFactory.openSession();
//Begin a Transaction
System.out.println("Begin a Transaction");
session.beginTransaction();
//Use the session to save the contact
System.out.println("Use the session to save the contact");
try{
session.save(contact);
} catch(Exception e) {
// Close the session
shutdown();
throw e;
}
//Commit the transaction
System.out.println("Commit the transaction");
session.getTransaction().commit();
// Close the session
System.out.println("Close the session");
session.close();
}
private static SessionFactory buildSessionFactory()
{
try
{
if (sessionFactory == null)
{
Configuration configuration = new Configuration().configure(Application.class.getResource("/hibernate.cfg.xml"));
StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();
serviceRegistryBuilder.applySettings(configuration.getProperties());
ServiceRegistry serviceRegistry = serviceRegistryBuilder.build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
}
return sessionFactory;
} catch (Throwable ex)
{
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory()
{
return sessionFactory;
}
public static void shutdown()
{
getSessionFactory().close();
}
}
I am doing all the right things, I have already checked that the
#Entity import has right package
package com.hibernate.demo.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Contact {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column
private String firstName;
#Column
private String lastName;
#Column
private String email;
#Column
private Long phone;
public Contact() {
}
public Contact(ContactBuilder contactBuilder) {
this.firstName = contactBuilder.firstName;
this.lastName = contactBuilder.lastName;
this.email = contactBuilder.email;
this.phone=contactBuilder.phone;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Long getPhone() {
return phone;
}
public void setPhone(Long phone) {
this.phone = phone;
}
#Override
public String toString() {
return "Contact [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email
+ ", phone=" + phone + "]";
}
public static class ContactBuilder {
private String firstName;
private String lastName;
private String email;
private Long phone;
public ContactBuilder(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public ContactBuilder withEmail(String email) {
this.email = email;
return this;
}
public ContactBuilder withPhone(Long phone) {
this.phone = phone;
return this;
}
public Contact build() {
return new Contact(this);
}
}
}
configuration.addAnnotatedClass(Contact.class);
resolves the issue, which is weird because it means
<mapping class="com.contact.model.Contact"/>
is not doing it for you. I don't like xml configuration anyways, good riddance.

spring boot data jpa mysql could not create database

I am new in spring
I will post my code,
that the application.properties
spring.datasource.url=jdbc:mysql://localhost/spring
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect
spring.jpa.hibernate.ddl-auto=update
and this my entity
package model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Person {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String name;
private String phone;
private String adresse;
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 getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAdresse() {
return adresse;
}
public void setAdresse(String adresse) {
this.adresse = adresse;
}
public Person(long id, String name, String phone, String adresse) {
super();
this.id = id;
this.name = name;
this.phone = phone;
this.adresse = adresse;
}
public Person() {
super();
}
}
and this is the repository
package repositry;
import org.springframework.data.jpa.repository.JpaRepository;
import model.Person;
public interface PersonRespositry extends JpaRepository<Person, Long> {
}
and my controller
package contoller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import model.Person;
import repositry.PersonRespositry;
#RestController
public class PersonController {
PersonRespositry rp;
#Autowired
public PersonController(PersonRespositry rp) {
// TODO Auto-generated constructor stub
this.rp=rp;
}
#RequestMapping("/find")
public Person find(long id){
return rp.findOne(id);
}
#RequestMapping("/findall")
public List<Person> findall(){
return rp.findAll();
}
#RequestMapping(value="/hello")
public String Demo(){
return "Hello world !!";
}
#RequestMapping(value="/create", method=RequestMethod.GET)
public String create(){
Person p=new Person();
p.setName("med");
p.setPhone("233888");
p.setAdresse("rue ");
rp.save(p);
return " success";
}
}
This is the architect of the project:
When I run the application the database does not generate and only the
localhost:8080 is running.
Your problem is the location of the Application.java.
#ComponentScanlooks for Spring beans inside the package of the class annotated with (#SpringBootApplication contains #ComponentScan) and in subpackages of this package.
I already provided an example to a very similar setup.
Please have a look here: https://stackoverflow.com/a/27983870/2576531
Furthermore the hint of Robert Moskal is correct. The database itself has to exist already. Only the tables will be created automatically.
If you want the data to be created you need to use create or create-drop. If you are using something like mysql you'll need to have created at least the database. The tables will be created for you.
I be very careful about doing this against a production database instance.
Otherwise for me it dosen't work with #componentScan but it works now with #EntityScan(basePackages = { "com.jwt.entites" }) in the main class to scan entity classes ..
This is not the answer but this is a sample. I think this will help you
//Pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.wisdom.spring.myjdbc</groupId>
<artifactId>spring_boot_jpa</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring_boot_jpa</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
//application Config
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost/wisdom
spring.datasource.username=root
spring.datasource.password=8855
spring.jpa.generate-ddl=true
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
server.port = 8585
package com.wisdom.spring.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.wisdom.spring.model.students;
import com.wisdom.spring.repo.students_repo;
#RestController
#RequestMapping("/students")
public class studentController {
#Autowired
students_repo STDRepo;
#GetMapping(value = "/a")
public String a() {
return "hello";
}
#GetMapping(value = "/save")
public List<students> getStudents(){
System.out.println("Data returned");
return STDRepo.findAll();
}
#PostMapping(value = "/savestd")
public void saveBurger(students student) {
STDRepo.save(student);
}
}
package com.wisdom.spring.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class students {
#Id
#Column
private int s_id;
#Column
private String name;
#Column
private String address;
public students() {
}
public students(int s_id, String name, String address) {
this.s_id = s_id;
this.name = name;
this.address = address;
}
public int getS_id() {
return s_id;
}
public void setS_id(int s_id) {
this.s_id = s_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
package com.wisdom.spring.repo;
import org.springframework.data.jpa.repository.JpaRepository;
import com.wisdom.spring.model.students;
public interface students_repo extends JpaRepository<students,String> {
}
package com.wisdom.spring;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class SpringBootJpaApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootJpaApplication.class, args);
}
}

Repeated column in mapping for entry error

I am doing a simple hibernate program in which I use Attribute override and Embedded object keys and I got this error:
Exception in thread "main" org.hibernate.MappingException: Repeated
column in mapping for entity: com.hibernate.Model.Employee column:
pincode (should be mapped with insert="false" update="false")
Employee.java
package com.hibernate.Model;
import javax.persistence.AttributeOverride;
import javax.persistence.AttributeOverrides;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table (name="EMPLOYEE")
public class Employee {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String firstName;
private String LastName;
private String email;
private String phoneNo;
#Embedded
#AttributeOverrides({
#AttributeOverride (name="City" , column=#Column(name="OFFICE_CITY")),
#AttributeOverride (name="State", column=#Column(name="OFFICE_STATE")),
#AttributeOverride (name="Country", column=#Column(name="OFFICE_COUNTRY")),
#AttributeOverride (name="pinCode", column=#Column(name="OFFICE_PINCODE"))})
private Address officeAddress;
#Embedded
private Address homeAddress;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return LastName;
}
public void setLastName(String lastName) {
LastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhoneNo() {
return phoneNo;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
public Address getOfficeAddress() {
return officeAddress;
}
public void setOfficeAddress(Address officeAddress) {
this.officeAddress = officeAddress;
}
public Address getHomeAddress() {
return homeAddress;
}
public void setHomeAddress(Address homeAddress) {
this.homeAddress = homeAddress;
}
}
Address.java
package com.hibernate.Model;
import javax.persistence.Embeddable;
#Embeddable
public class Address {
private String City;
private String State;
private String Country;
private String pincode;
public String getCity() {
return City;
}
public void setCity(String city) {
City = city;
}
public String getState() {
return State;
}
public void setState(String state) {
State = state;
}
public String getCountry() {
return Country;
}
public void setCountry(String country) {
Country = country;
}
public String getPincode() {
return pincode;
}
public void setPincode(String pincode) {
this.pincode = pincode;
}
}
Hibernate.jsp
package com.hibernate.Test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.hibernate.Model.Address;
import com.hibernate.Model.Employee;
public class HibernateTest {
public static void main(String[] args) {
Employee emp = new Employee();
Address addr=new Address();
emp.setFirstName("Vikas");
emp.setLastName("Bhardwaj");
emp.setEmail("bhardwajvikas93#gmail.com");
emp.setPhoneNo("9741178304");
addr.setCity("MEHRE");
addr.setCountry("INDIA");
addr.setState("HIMACHAL");
addr.setPincode("174305");
emp.setHomeAddress(addr);
Address addr2 = new Address();
addr2.setCity("Bangalore");
addr2.setCountry("INDIA");
addr2.setState("KARNATKA");
addr2.setPincode("560008");
emp.setOfficeAddress(addr2);
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session ssn = sf.openSession();
ssn.beginTransaction();
ssn.save(emp);
ssn.getTransaction().commit();
ssn.close();
}
}
cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!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>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/HibernateDb</property>
<property name="connection.username">root</property>
<property name="connection.password">vikas</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
<!-- Names the annotated entity class -->
<mapping class="com.hibernate.Model.Employee"/>
<mapping class="com.hibernate.Model.Address"/>
</session-factory>
</hibernate-configuration>
In this program by embedable, I am printing both member variables in one table.
The task is with address class, I am printing two addresses. One is for home address and one is for office address by using AttributeOverrides but it gives me the error mentioned above.
You need to specify a valid property name pincode
#AttributeOverride (name="pinCode", column=#Column(name="OFFICE_PINCODE"))
need to change to
#AttributeOverride (name="pincode", column=#Column(name="OFFICE_PINCODE"))
Try to specify #AttributeOverrides for homeAddress, if it will not help.

How can I change this configuration so I can work with Hibernate?

This is my project structure:
I have these following files:
context.xml
<?xml version='1.0' encoding='utf-8'?>
<Context>
<Resource name="jdbc/sakila"
url="jdbc:mysql://localhost/sakila"
username="root"
password=""
driverClassName="com.mysql.jdbc.Driver"
type="javax.sql.DataSource"
maxActive="20" maxIdle="5" maxWait="10000"
/>
</Context>
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<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="sakila" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<non-jta-data-source>java:comp/env/jdbc/sakila</non-jta-data-source>
</persistence-unit>
</persistence>
And in a DAO class I can use:
EntityManagerFactory sakilaFactory = Persistence.createEntityManagerFactory("sakila");
EntityManager entityManager = sakilaFactory.createEntityManager();
which all works fine..
But I want to change my configuration to using .xml files and instead of EntityManager I want to use Session from Hibernate API.
I have looked at several tutorials on the web but I am only more confused. How should I use the .xml files for Hibernate configuration?
I am running the application on Tomcat and here is my dependencies from pom.xml
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.10.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.10.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
<scope>provided</scope>
</dependency>
What I want to achieve is a proper Hibernate configuration, and using Session instead of EntityManager.
Edit #1: This is what my Actor class looks like:
package biz.tugay.model;
/* User: koray#tugay.biz Date: 06/08/15 Time: 09:17 */
import javax.persistence.*;
import java.sql.Timestamp;
#Entity
#Table(name = "actor")
public class Actor {
private Integer actor_id;
private String first_name;
private String last_name;
private Timestamp last_update;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
public Integer getActor_id() {
return actor_id;
}
public void setActor_id(Integer id) {
this.actor_id = id;
}
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public Timestamp getLast_update() {
return last_update;
}
public void setLast_update(Timestamp last_update) {
this.last_update = last_update;
}
#Override
#Transient
public String toString() {
return "Actor{" +
"id=" + actor_id +
", first_name='" + first_name + '\'' +
", last_name='" + last_name + '\'' +
", last_update=" + last_update +
'}';
}
}
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:PORT/databasename</property>
<property name="hibernate.connection.username">username</property>
<property name="hibernate.connection.password">XXXX</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">create </property>
<property name="hbm2ddl.auto">validate</property>
<mapping class="com.packageClass"/>
<mapping class="com.package.OtherClass"/>
</session-factory>
you should have the hibernate.cfg.xml - configuration file for hibernate; i gave you a template above.It should be placed in the src of your java resources. Now you can use annotations for persistance. And you should also add #Column annotation on every attribute in you actor class to map every attribute on an attribute from your table.Here is an example class
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="useri")
public class User implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Integer id_user;
#Column(name="username")
private String username;
#Column(name="password")
private String password;
#Column(name="rol")
private String rol;
public Integer getId_user() {
return id_user;
}
public void setId_user(Integer id_user) {
this.id_user = id_user;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRol() {
return rol;
}
public void setRol(String rol) {
this.rol = rol;
}
public User() {
}
}

Categories

Resources