Hibernate: object.org.hibernate.MappingException - java

Here is the exception i am facing, it occurs when i call session.save
object.org.hibernate.MappingException: Unknown entity:
com.java.learn.pojo.Employee
here is my java code
try
{
Configuration configuration = new Configuration().configure();
StandardServiceRegistryBuilder builder =
new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
SessionFactory factory = configuration.buildSessionFactory(builder.build());
Session session = factory.openSession();
Employee e = new Employee(1, "", "", 3);
e.setFirstName("sparsh");
session.save(e);
System.out.println("in dao");
}
catch (Throwable ex)
{
System.err.println("Failed to create sessionFactory object." + ex);
factory.close();
throw new ExceptionInInitializerError(ex);
}
and here is my hibrnate.cfg.xml
<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 students is the database name -->
<property name="hibernate.connection.url">
jdbc:mysql://localhost/test
</property>
<property name="hibernate.connection.username">
root
</property>
<property name="hibernate.connection.password">
root1
</property>
<property name="hbm2ddl.auto">create</property>
<property name="show_sql">true</property>
<mapping class="com.java.learn.pojo.Employee"/>
</session-factory>
</hibernate-configuration>
this exception occurs because of no mapping for Pojo class, but I have added it.
Pojo class
package com.java.learn.pojo;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Table
#Entity
public class Employee
{
#Id
#GeneratedValue
#Column(name = "id")
private int id;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#Column(name = "salary")
private int salary;
public Employee()
{
}
public Employee(int id, String firstName, String lastName, int salary)
{
super();
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.salary = salary;
}
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public String getFirstName()
{
return firstName;
}
public void setFirstName(String first_name)
{
this.firstName = first_name;
}
public String getLastName()
{
return lastName;
}
public void setLastName(String last_name)
{
this.lastName = last_name;
}
public int getSalary()
{
return salary;
}
public void setSalary(int salary)
{
this.salary = salary;
}
}
Please help

You can use new Configuration().configure() to load the Entity mappings from hbm.xml files.
But because you are using annotations for your Employee Entity class, you simply need to use AnnotationConfiguration instead of Configuration as shown below:
So, replace the line below:
Configuration configuration = new Configuration().configure();
with:
Configuration configuration = new AnnotationConfiguration().configure();

Problem:
The problem is obvious here, you have not correctly mapped your Employee entity which is so relevant from the error stack trace:
object.org.hibernate.MappingException: Unknown entity: com.java.learn.pojo.Employee
And the problem is that the mapped entity in your hibernate.cfg.xml configuration file can't be reached because you placed your file under web-inf/classes so when hibernate tries to look for your Entity it will look for it under web-inf/classes and it won't find it.
Solution:
To solve this problem you just need to place your hibernate.cfg.xml file under Java/src folder instead of web-inf/classes so the Entity can be reached.

Related

Hibernate Save Entity to Mysql

Here is my project structure:
I'm trying to save a Patient Entity to my database using hibernate:
PatientController.java
#RestController
public class PatientController {
#Autowired
PatientRepository patientRepository;
#GetMapping("/patients")
public List<Patient> getPatients(){
SessionFactory factory = new Configuration().configure("/com/nbu/projects/dentistappointmentsys/hibernate.cfg.xml")
.buildSessionFactory();
Session session = factory.openSession();
//Add new Patient object
Patient p1 = new Patient();
p1.setEmail("lokesh#mail.com");
p1.setFirstName("lokesh");
p1.setLastName("gupta");
p1.setPassword("gupta123");
//Save the patient in database
session.save(p1);
session.flush();
session.close();
return patientRepository.findAll();
}
Patient.java
#Entity
public class Patient {
#Id
#GeneratedValue
Long id;
String firstName;
String lastName;
String email;
String password;
public Long getId() {
return id;
}
public void setId(Long 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 String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Patient(){}
public Patient(String firstName, String lastName, String email, String password) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.password = password;
}
}
PatientRepository
public interface PatientRepository extends JpaRepository {
}
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://localhost:3306/dentist-appointment-sys</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<property name="connection.autocommit">true</property>
<mapping class="com.nbu.projects.dentistappointmentsys.models.Patient"></mapping>
</session-factory>
</hibernate-configuration>
HibernateUtil
public class HibernateUtil
{
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory()
{
try {
return new Configuration().configure("/com/nbu/projects/dentistappointmentsys/hibernate.cfg.xml").buildSessionFactory();
} 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() {
// Close caches and connection pools
getSessionFactory().close();
}
}
In the fron end I have an http get like so:
public getPatients(): Observable<Patient[]> {
return this.httpClient.get('patients');
}
So far I was able to read my Patient data from my db, but now that I've tried to update the db I get the This Error
Can anybody tell me what I'm doing wrong, since I'm new to hibernate and I'm probably mistaking in my configuration etc..
Error says it all
Not able to locate hibernate.cfg.xml
so the problem is in this line
return new Configuration().configure("/com/nbu/projects/dentistappointmentsys/hibernate.cfg.xml").buildSessionFactory();
As far as I can see your HibernateUtils is in same place where hibernate.cfg.xml is
so just try
return new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
and it should work
getting file reference works relatively.
you have to start from source file where you are accessing your file and all way to target file
I fixed it by moving my hibernate.cgf.xml to src/main/resources. To anybody who is having the same issue - check if after you compile the hibernate config file shows up in target/classes, as it should if you've placed it under resources
You can paste your "hibernate.cfg.xml" file to the src\main\resources\hibernate.cfg.xml:
Then in the HibernateUtil file,please change as below:
return new Configuration().configure().buildSessionFactory().openSession();

Hibernate can't find my hibernate.cfg.xml file

Pretty stupid/simple question. Doing an assignment and hibernate can't find my hibernate.cfg.xml file. I'm using IntelliJ and it is located inside my src folder. See my code below.
Main:
public class Main {
public static void main(String[] args) {
Employee tempEmployee = new Employee("Ronald", "Customer Service", true);
EmployeeDAO employeeDAO = new EmployeeDAO();
employeeDAO.saveEmployee(tempEmployee);
}
}
DAO:
public class EmployeeDAO {
SessionFactory sessionFactory = new Configuration()
.configure()
.addAnnotatedClass(Employee.class)
.buildSessionFactory();
public void saveEmployee(Employee employee){
Session session = sessionFactory.getCurrentSession();
try {
session.beginTransaction();
session.save(employee);
session.getTransaction().commit();
} finally {
session.close();
}
}
}
Entity:
#Entity
#Table(name = "employee")
public class Employee {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private long id;
#Column(name = "name")
private String name;
#Column(name = "department")
private String department;
#Column(name = "working")
private boolean working;
public Employee(){}
public Employee(String name, String department, boolean working) {
this.name = name;
this.department = department;
this.working = working;
}
#Override
public String toString() {
return "Employee{" +
"id=" + id +
", name='" + name + '\'' +
", department='" + department + '\'' +
", working=" + working +
'}';
}
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 getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public boolean isWorking() {
return working;
}
public void setWorking(boolean working) {
this.working = working;
}
}
Hibernate config:
<?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:3306/employee</property>
<property name="connection.username">employee</property>
<property name="connection.password">employee</property>
<property name="dialect">com.hibernate.dialect.MySQL5Dialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<property name="current_session_context_class">thread</property>
</session-factory>
</hibernate-configuration>
add configuration.configure("classpath:com/resources/hibernate.cfg.xml"); this will locate your hibernate cfg.xml file also
read this tutorial
Mark your resources folder as resources from INTELLIJ IDEA.
Go to: File->Project Structure to do it.
Hope, it helps.
Put your XML configuration file hibernate.cfg.xml under src/main/resources.
Also you can add it manually using File → Project Structure → Add → Hibernate:
And then add a descriptor in the same window as:
specify the path to your descriptor and press OK.

MySQL table not mapped by Hibernate 5+

I'm trying to learn Hibernate using MySQL built-in database named world. It has three tables called city, country and countrylanguage. What I'm trying to do is execute SQL statement SELECT * FROM world.city;. When I run my project I'm getting error
org.hibernate.hql.internal.ast.QuerySyntaxException: City is not mapped [from City]
I'm using IntelliJ IDEA and Hibernate 5.2.8.
I created mapping xml file like this:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="pl.hibernatePackage">
<class name="City" table="city">
<id name="id" column="ID" type="int">
<generator class="native"/>
</id>
<property name="name" column="Name" type="string"/>
<property name="countryCode" column="CountryCode" type="string"/>
<property name="district" column="District" type="string"/>
<property name="population" column="Population" type="int"/>
</class>
</hibernate-mapping>
City.java is presented below:
public class City
{
private Integer id;
private String name;
private String countryCode;
private String district;
private Integer population;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCountryCode() {
return countryCode;
}
public void setCountryCode(String countryCode) {
this.countryCode = countryCode;
}
public String getDistrict() {
return district;
}
public void setDistrict(String district) {
this.district = district;
}
public Integer getPopulation() {
return population;
}
public void setPopulation(Integer population) {
this.population = population;
}
}
I'm creating session in HibernateUtil.java
public class HibernateUtil
{
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
Configuration configuration = new Configuration();
configuration.configure();
StandardServiceRegistryBuilder standardServiceRegistryBuilder = new StandardServiceRegistryBuilder();
standardServiceRegistryBuilder.applySettings(configuration.getProperties());
ServiceRegistry serviceRegistry = standardServiceRegistryBuilder.build();
return configuration.buildSessionFactory(serviceRegistry);
}
catch(Exception e) {
throw new ExceptionInInitializerError(e);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Configuration 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.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/world</property>
<property name="hibernate.connection.username">test</property>
<property name="hibernate.connection.password">1234</property>
<property name="connection.pool_size">1</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="current_session_context_class">thread</property>
<property name="show_sql">false</property>
<property name="hbm2ddl.auto">update</property>
<!-- List of XML mapping files -->
<mapping resource="pl/hibernatePackage/City.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Main
public class Main
{
public static void main(String[] args)
{
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
List<City> cities = session.createQuery("from City").list();
for(City c : cities) {
System.out.println(c.getId() + "\t" + c.getName() + "\t" + c.getCountryCode() + "\t" + c.getDistrict() +
"\t" + c.getPopulation());
}
session.getTransaction().commit();
HibernateUtil.getSessionFactory().close();
}
}
EDIT Full error list
EDIT 2
javac result
I have done some testing and i made it work by using the fully qualified class name:
session.createQuery("from pl.hibernatePackage.City")
Now this is only a workaround without touching your config..
After digging deeper i found out that since hibernate version 5.x, there is a different strategy for building the sessionFactory.
I made your example work by implementing sessionFactory as follows:
StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
.configure()
.build();
Metadata metadata = new MetadataSources( standardRegistry )
.getMetadataBuilder()
.build();
return configuration.buildSessionFactory(serviceRegistry);
This is explained with example here: jboss documentation (point 2.4)
Thanks to Maciej's answer and help of other guys I managed to get my example to work by modifying code and cleaning it up a little. I also found out that mapping DB with xml file is outdated so I modifiied properly CityEntity class. Final code:
Main.java
import org.hibernate.Session;
import java.util.List;
public class Main
{
public static void main(String[] args)
{
Session session = HibernateUtil.getSession();
session.beginTransaction();
List<CityEntity> cities = session.createQuery("from CityEntity").list();
for(CityEntity c : cities)
{
System.out.println(c.getId() + "\t" + c.getName() + "\t" + c.getCountryCode() + "\t" + c.getDistrict() +
"\t" + c.getPopulation());
}
session.getTransaction().commit();
HibernateUtil.close();
}
}
hibernate.cfg.xml
<?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.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/world</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">1234</property>
<property name="connection.pool_size">1</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<!-- List of mapped classes -->
<mapping class="CityEntity"/>
</session-factory>
</hibernate-configuration>
HibernateUtil.java
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;
public class HibernateUtil
{
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
Configuration configuration = new Configuration();
configuration.configure();
StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
.configure()
.build();
return configuration.buildSessionFactory(standardRegistry);
}
catch(Exception e) {
throw new ExceptionInInitializerError(e);
}
}
public static Session getSession()
{
return sessionFactory.openSession();
}
public static void close()
{
sessionFactory.close();
}
}
CityEntity.java
import javax.persistence.*;
#Entity
#Table(name = "city", schema = "world")
public class CityEntity
{
private int id;
private String name;
private String countryCode;
private String district;
private int population;
#Basic
#Column(name = "CountryCode")
public String getCountryCode() {
return countryCode;
}
public void setCountryCode(String countryCode) {
this.countryCode = countryCode;
}
#Id
#Column(name = "ID")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Basic
#Column(name = "Name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Basic
#Column(name = "District")
public String getDistrict() {
return district;
}
public void setDistrict(String district) {
this.district = district;
}
#Basic
#Column(name = "Population")
public int getPopulation() {
return population;
}
public void setPopulation(int population) {
this.population = population;
}
}

Exception in thread "main" org.hibernate.exception.SQLGrammarException: ORA-02289: sequence does not exist

I am trying to execute a basic hibernate application.However,I am consistently getting the error that is posted in the question.
Below posted is my project structure code:
Below is the code that is present in app.java
public class app {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Session session =hibernate_utils.getSessionFactory().openSession();
session.beginTransaction();
contact contact=new contact();
contact.setFirstname("xxx");
contact.setLastname("xxx");
contact.setEmail("xxxxxxx#gmail.com");
contact.setTelephone("xxxxxxxxxx");
session.save(contact);
session.getTransaction().commit();
System.out.println("saved");
}
}
Below posted is the code that is present in the contact.java file
package net.rishanth.contact.form;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Column;
import static javax.persistence.GenerationType.SEQUENCE;
#Entity
#Table(name = "contacts")
public class contact {
#Id
#GeneratedValue(strategy=SEQUENCE)
#Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "firstname", nullable = false)
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
#Column(name = "lastname", nullable = false)
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
#Column(name = "email", nullable = false)
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Column(name = "telephone", nullable = false)
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
private String firstname;
private String lastname;
private String email;
private String telephone;
private Integer id;
}
Below posted is the code for my hiber_utils class present in service package.
package net.rishanth.contact.service;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class hibernate_utils {
private static final SessionFactory sessionfactory= buildSessionFatory();
#SuppressWarnings("deprecation")
private static SessionFactory buildSessionFatory(){
// TODO Auto-generated method stub
return new Configuration().configure().buildSessionFactory();
}
public static SessionFactory getSessionFactory()
{
return sessionfactory;
}
public static void shutdown()
{
getSessionFactory().close();
}
}
Below present is the hibernate.cnfg.xml file
<?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.bytecode.use_reflection_optimizer">false</property>
<property
name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver
</property>
<property
name="hibernate.connection.url">jdbc:oracle:thin:#127.0.0.1:1521:XE
</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect
</property>
<property name="hibernate.connection.username">system</property>
<property name="hibernate.connection.password">xxxxx</property>
<mapping class="net.rishanth.contact.form.contact"></mapping>
</session-factory>
</hibernate-configuration>
Below attached is my oracle screenshot
Any help would be highly appreciated.
Thanks!
You have annotated the Contact entity use SEQUENCE as strategy. But you have not specified which sequence should be used. (I believe this is the error you might be getting. If not, posting the exception stack trace will help.)
In this case, by default hibernate looks for a sequence named hibernate_sequence and creating a sequence with this name should help.
Or, In case you want hibernate to use a sequence (say, your_sequence_name) that you have already created then further qualifying the #Id attribute as below should help:
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="mySeq")
#GenericGenerator(name="mySeq", strategy="sequence",
parameters={
#Parameter(name="sequence_name", value="your_sequence_name")
})
Usually we need not to create the table/sequence in our DB, hibernate can manage the same.
For that you need to add below tag in your hibernate.cfg.xml
<property name="hbm2ddl.auto">create</property>
hbm2ddl.auto have few possible values:
create : When you create SessionFactory, hibernate drop everything(if exist) and create it again for you.
create-drop : create everything on start-up and drop them on shut-down
update : update the schema.
validate : validate the schema, makes no changes to the database.
Anyway, if you want to create table/sequence explicitly, you can create them.
But then while using #GeneratedValue you have to specify your sequence.

#Formula pattern in hibernate

I was reading some interview questions on Hibernate and came across Hibernate derived properties. I was trying a simple example using #Formula annotations but it is not working. Can anyone please tell me what am i missing. Code snippets below
The output and the SQL queries are display at the end.
Entity (Employee.java)
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.Formula;
#Entity
#Table(name="EMPLOYEE")
public class Employee implements java.io.Serializable {
private static final long serialVersionUID = -7311873726885796936L;
#Id
#Column(name="ID")
private Integer id;
#Column(name="FIRST_NAME", length=31)
private String firstName;
#Column(name="LAST_NAME", length=31)
private String lastName;
#Column(name="MONTHLY_SALARY")
private float monthlySalary;
#Formula("MONTHLY_SALARY*12")
private float yearlySalary;
public Employee() {
}
public Integer getId() {
return id;
}
public void setId(Integer 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 float getMonthlySalary() {
return monthlySalary;
}
public void setMonthlySalary(float monthlySalary) {
this.monthlySalary = monthlySalary;
}
public float getYearlySalary() {
return yearlySalary;
}
}
hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle9iDialect</property>
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.username">system</property>
<property name="hibernate.connection.password">system</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:#localhost:1521:XE</property>
<property name="hibernate.cache.use_query_cache">false</property>
<property name="hibernate.jdbc.use_streams_for_binary">true</property>
<property name="hibernate.jdbc.batch_size">0</property>
<property name="hibernate.max_fetch_depth">3</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<property name ="show_sql">true</property>
<mapping class="Employee"/>
<!-- <mapping class="dto.UserDetailsEmbeddedId"/>-->
</session-factory>
</hibernate-configuration>
Tester class
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateTest {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
SessionFactory factory = (new Configuration()).configure().buildSessionFactory();
Session session = factory.openSession();
Employee employee = new Employee();
employee.setFirstName("Tarun");
employee.setLastName("bhatt");
employee.setMonthlySalary(34000);
employee.setId(12);
session.beginTransaction();
session.save(employee);
session.getTransaction().commit();
System.out.println("salary1 = "+employee.getYearlySalary());
session.close();
System.out.println("salary = "+employee.getYearlySalary());
}
}
Output
salary1 = 0.0
salary = 0.0
Queries
Hibernate: create table EMPLOYEE (ID number(10,0) not null, FIRST_NAME varchar2(31 char), LAST_NAME varchar2(31 char), MONTHLY_SALARY float, primary key (ID))
Hibernate: insert into EMPLOYEE (FIRST_NAME, LAST_NAME, MONTHLY_SALARY, ID) values (?, ?, ?, ?)
#Formula annotation is intended to be used during data-retrivial (SELECT in few words) so a read of and Employee looks as
select ID,FIRST_NAME,LAST_NAME,MONTHLY_SALARY,MONTHLY_SALARY*12 as yearlySalary
#Formula doesn't works for insertion or update

Categories