INFO: HHH10001008: Cleaning up connection pool [jdbc:mysql://localhost:3306/hb_student_tracker?useSSL=false&serverTimezone=UTC]
Exception in thread "main" org.hibernate.PropertyAccessException:
Could not set field value [POST_INSERT_INDICATOR] value by reflection
: [class com.luvjava.hibernate.demo.entity.Student.id] setter of
com.luvjava.hibernate.demo.entity.Student.id at
org.hibernate.property.access.spi.SetterFieldImpl.set(SetterFieldImpl.java:72)
at
com.luvjava.hibernate.demo.CreateStudentDemo.main(CreateStudentDemo.java:33)
Caused by: java.lang.IllegalArgumentException: Can not set int field
com.luvjava.hibernate.demo.entity.Student.id to
org.hibernate.id.IdentifierGeneratorHelper$2
error comes when saving student object in CreateStudentDemo.class
CreateStudentDemo.class
package com.luvjava.hibernate.demo;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.luvjava.hibernate.demo.entity.Student;
public class CreateStudentDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
//create session factory
SessionFactory factory=new Configuration()
.configure("hibernate.cfg.xml")
.addAnnotatedClass(Student.class)
.buildSessionFactory();
//create session object
Session session=factory.getCurrentSession();
System.out.println("before try block");
//save object
try {
//begin transaction
session.beginTransaction();
System.out.println("Creating student object..");
//create object
Student theStudent=new Student("Ravisher","Singh","rvsingh3213#gmail.com");
//save object
System.out.println("Saving Student Object...");
session.save(theStudent); **This is line from where exception starts**
System.out.println(" afterSaving Student Object...");
//commit changes
session.getTransaction().commit();
System.out.println("commit Done");
}
finally {
session.flush();
session.close();
factory.close();
}
}
}
This is Entity class
package com.luvjava.hibernate.demo.entity;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="student")
public class Student {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="id")
private int id;
#Id
#Column(name="first_Name" )
private String firstName;
#Id
#Column(name="last_Name")
private String lastName;
#Id
#Column(name="email")
private String email;
public Student() {
System.out.println("In default constructor");
}
//Constructor using fields
public Student(String firstName, String lastName, String email) {
System.out.println("arg constructor.");
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 will be 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>
You need only one #Id annotation in your entity class
Here is how your entity should look
#Entity
#Table(name="student")
public class Student {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="id")
private int id;
#Column(name="first_Name" ) <--- first_Name, this value MUST MATCH WITH WHAT YOU HAVE IN YOUR DATABASE
private String firstName;
#Column(name="last_Name")<--- last_Name, this value MUST MATCH WITH WHAT YOU HAVE IN YOUR DATABASE
private String lastName;
#Column(name="email")
private String email;
public Student() {
System.out.println("In default constructor");
}
//Constructor using fields
public Student(String firstName, String lastName, String email) {
System.out.println("arg constructor.");
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 + "]";
}
}
Related
So I am doing just a simple code in hibernate and its saying "No exception of type HibernateException can be thrown". What to do?
My Code:
XML File:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/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/testdb</property>
<property name="connection.username">root</property>
<property name="connection.password">Stormbreaker0811</property>
<property name="connection.pool_size">1</property>
<property name="dialect">org.hibernate.dialect.MySQL57Dialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<property name="current_session_context_class">thread</property>
<mapping class="com.hibernate.Student"/>
</session-factory>
</hibernate-configuration>
POJO Class:
package com.hibernate;
import org.hibernate.annotations.Columns;
import org.hibernate.annotations.Entity;
import org.hibernate.annotations.Table;
#Entity
#Table(name = "student")
public class Student {
#Id
#Column(name="ID")
private int id;
#Column(name="NAME")
private String name;
#Column(name="EMAIL")
private String email;
#Column(name="GENDER")
private String gender;
#Column(name="AGE")
private int age;
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;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
And the Main Class:
package com.hibernate;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class Student_Main {
private static SessionFactory factory;
public static void main(String[] args) throws Exception {
try {
factory = new org.hibernate.cfg.Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(Student.class).buildSessionFactory();
} catch (Exception | HibernateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Any Solution on this?
I tied to handle with just Exception class but still it tells me to add throws declaration or catch method. I was expecting for the problemto be gone but still not gone.
I am trying to build a Spring Boot application that uses 2 data sources. My primary database for now is the in-memory database (just for testing purposes) with tables that are populated with the help of the sql file that I have created. The other database(oracledb) has tables that are already populated.
What am I trying to achieve?
I am trying to pull data from oracledb, process it and populate tables in h2 database.
What is the problem I am facing?
I only want the entities for the h2 db be created as tables in the in-mem database (I want to be able to specify h2 which entities to scan and create tables, not all the classes that have #Entity annotation). All of the classes that have #Entity are being created as tables in my in-mem database and that is what I am trying to avoid.
What have I tried?
I created two separate packages for the entities belonging to h2 and oracledb and using #EntityScan I only scanned the package that had entities for h2. This worked, however, I need the other entities for oracledb to be scanned so I am able to use them.
Code Snippet of what I have:
My applications.properties file
#spring.jpa.hibernate.ddl-auto=none
spring.jpa.generate-ddl=true
spring.h2.console.enabled=true
spring.h2.console.path=/h2
# first data source
spring.datasource.url=jdbc:h2:mem:mydb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.application.name=Health Monitor
## 2nd data source
spring.production-datasource.url= jdbc:oracle://localhost:3306/db2
spring.production-datasource.driverClassName=oracle.jdbc.driver.OracleDriver
spring.production-datasource.username=abcd
spring.production-datasource.password=xyz123
DemoApplication.java
package com.automation.demo;
import java.sql.SQLException;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Bean;
#SpringBootApplication
//#EntityScan( basePackages = {"domain"} )
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
#Bean(initMethod = "start", destroyMethod = "stop")
public org.h2.tools.Server inMemoryH2DatabaseaServer() throws SQLException {
return org.h2.tools.Server.createTcpServer(
"-tcp", "-tcpAllowOthers", "-tcpPort", "9090");
}
}
ConfigureDB.java
package com.automation.demo.configurations;
import javax.sql.DataSource;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import com.zaxxer.hikari.HikariDataSource;
#Configuration
public class ConfigureDB {
#Primary
#Bean
#ConfigurationProperties(prefix="spring.datasource")
public DataSourceProperties devDataSourceProperties() {
return new DataSourceProperties();
}
#Bean
#Primary
#ConfigurationProperties("spring.datasource.configuration")
public DataSource devDataSource() {
return devDataSourceProperties().initializeDataSourceBuilder()
.type(HikariDataSource.class).build();
}
#Bean
#ConfigurationProperties("spring.production-datasource")
public DataSourceProperties productionDataSourceProperties() {
return new DataSourceProperties();
}
#Bean
#ConfigurationProperties("spring.production-datasource.configuration")
public DataSource productionDataSource() {
return productionDataSourceProperties().initializeDataSourceBuilder()
.type(HikariDataSource.class).build();
}
}
Employee.java (for the h2 database)
package com.automation.demo.dev.entities;
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="test")
public class Employee {
// define fields
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="ID")
private int id;
#Column(name="FirstName")
private String firstName;
#Column(name="LastName")
private String lastName;
#Column(name="Email")
private String email;
// define constructors
public Employee() {
}
public Employee(String firstName, String lastName, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
// define getter/setter
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;
}
// define tostring
#Override
public String toString() {
return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]";
}
}
CustomerInfo.java (this is the entity representing a table in oracledb, I want to prevent a table representing this entity to be created in the h2 database)
package com.automation.demo.production.entities;
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="customer")
public class CustomerInfo {
// define fields
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="ID")
private int id;
#Column(name="FirstName")
private String firstName;
#Column(name="LastName")
private String lastName;
#Column(name="Email")
private String email;
// define constructors
public CustomerInfo() {
}
public CustomerInfo(String firstName, String lastName, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
// define getter/setter
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;
}
// define tostring
#Override
public String toString() {
return "Customer [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]";
}
}
Please let me know if I have missed anything. Also, if there are any other mistakes I have made but are not related to my current problem please mention those as well.
Thanks.
Hibernate has a way to do this with SchemaFilterProvider.
SchemaFilterProvider
public class MySchemaFilterProvider implements SchemaFilterProvider {
#Override
public SchemaFilter getCreateFilter() {
return MySchemaFilter.INSTANCE;
}
#Override
public SchemaFilter getDropFilter() {
return MySchemaFilter.INSTANCE;
}
#Override
public SchemaFilter getMigrateFilter() {
return MySchemaFilter.INSTANCE;
}
#Override
public SchemaFilter getValidateFilter() {
return MySchemaFilter.INSTANCE;
}
}
SchemaFilter
public class MySchemaFilter implements SchemaFilter {
public static final MySchemaFilter INSTANCE = new MySchemaFilter();
#Override
public boolean includeNamespace(Namespace namespace) {
return true;
}
#Override
public boolean includeTable(Table table) {
if (table.getName().equals("customer")) {
return false;
}
return true;
}
#Override
public boolean includeSequence(Sequence sequence) {
return true;
}
}
Spring property configuration
spring.jpa.properties.hibernate.hbm2ddl.schema_filter_provider=MySchemaFilterProvider
Note - With Springboot the property is: spring.jpa.properties.hibernate.hbm2ddl.schema_filter_provider=xxx
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();
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.
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