I connected data base with hibernate to my application with this settings:
hibernateContext.xml
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate4.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="hibernateUserDao" class="org.springframework.web.basepackage.HibernateUserDao">
<property name="hibernateTemplate" ref="hibernateTemplate" />
</bean>
this is 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>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/fullproject</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">admin</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.show_sql">true</property>
<mapping resource="user.hbm.xml" />
</session-factory>
</hibernate-configuration>
this is user.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="org.springframework.web.basepackage.User" table="users">
<id name="id" column="id">
<generator class="native" />
</id>
<property name="login" column="login"/>
<property name="password" column="password" />
<property name="email" column="email" />
</class>
</hibernate-mapping>
this is my user entity
public class User {
private int id;
private String login;
private String password;
private String email;
public User(){
}
public User(String login, String password, String email){
this.login = login;
this.password = password;
this.email = email;
}
public int getId(){
return id;
}
public String getLogin(){
return login;
}
public String getPassword(){
return password;
}
public String getEmail(){
return email;
}
public void setId(int id){
this.id = id;
}
public void setLogin(String login){
this.login = login;
}
public void setPassword(String password){
this.password = password;
}
public void setEmail(String email){
this.email = email;
}
}
when i try save db in this way "hibernateTemplate.save(user)' i catch in console this line
"Hibernate: insert into users (login, password, email) values (?, ?, ?)" and changes don't save into database. I tried in user.hbn.xml change generator class to "increment" because my id in data base table has AUTO INCREMENT parameter, but it doesn't work.
This sound like your transaction didn't get commit after update. When you call HibernateTemplate.update() it only update your persistent but doesn't actually to commit those changes. Remember to always conclude your transaction and save it before moving on.
Here are some resources on hibernate sessions and transactions that might help you with your current problem 1 and 2
Related
I'm using hibernate 5 and trying to save an object to my database. But for some reason, I'm always getting a
Exception in thread "main" org.hibernate.MappingException: Unknown entity: model.database.Customer.
For some reason, the Customer.hbm.xml is not being found. I really don't know why.
Customer.hbm.xml:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="model.database.Customer" table="CUSTOMER">
<id name="username" type="string">
<column name="USERNAME" length="8" />
<generator class="assigned"></generator>
</id>
<property name="password" type="string">
<column name="PASSWORD" length="8" />
</property>
<property name="lastname" type="string">
<column name="LASTNAME" length="20" />
</property>
<property name="firstname" type="string">
<column name="FIRSTNAME" length="20" />
</property>
</class>
</hibernate-mapping>
Customer.java:
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="CUSTOMER")
public class Customer implements java.io.Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="username", nullable=false)
private String username;
#Column(name="firstname")
private String firstname;
#Column(name="lastname")
private String lastname;
#Column(name="password")
private String password;
public Customer () {
}
public Customer(String username) {
this.username = username;
}
public Customer(String username, String firstname, String lastname, String password) {
this.username = username;
this.firstname = firstname;
this.lastname = lastname;
this.password = password;
}
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFirstname() {
return this.firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return this.lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
}
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.dialect">
org.hibernate.dialect.PostgreSQL81Dialect
</property>
<property name="hibernate.connection.driver_class">
org.postgresql.Driver
</property>
<property name="hibernate.connection.url">
jdbc:postgresql://localhost:5432/postgres
</property>
<property name="hibernate.connection.username">
postgres
</property>
<property name="hibernate.connection.password">
postgres
</property>
<property name="hibernate.current_session_context_class">
thread
</property>
<mapping resource="model/database/Customer.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Main:
public class Main {
public static void main(String[] args) {
Customer cstm = new Customer("lebetyp", "peter", "ja", "ja");
CustomerManager mngr = new CustomerManager();
mngr.saveCustomer(cstm);
}
}
HibernateUtil:
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory from hibernate.cfg.xml
Configuration configuration = new Configuration().configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory(builder.build());
System.out.println("Initial SessionFactory creation");
} catch (Throwable ex) {
System.out.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
How can I get rid of this exception to make it work. Is there missing a dependency? Or what am I doing wrong?
Add this to your hibernate.cfg.xml
remove <mapping resource="model/database/Customer.hbm.xml"/> and add
<mapping class="Customer"></mapping>.
I hope your Customer class has JPA annotations like #Entity , #Id etc in it.
This question already has answers here:
Maven Run Project
(6 answers)
Closed 7 years ago.
In Eclipse, I have been building a simple Hibernate+Spring+MySQL+Maven project recently.I am stuck at the stage of database&java connection.When I run the project, it gives the the following error:
Exception in thread "main" org.hibernate.MappingException: Unable to load class [ src/main/java/com.hibernate.data/Person] declared in Hibernate configuration <mapping/> entry
at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:2279)
at org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:2227)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2207)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2160)
at org.hibernate.cfg.Configuration.configure(Configuration.java:2075)
at com.test.Main.main(Main.java:17)
Caused by: java.lang.ClassNotFoundException:src/main/java/com.hibernate.data/Person
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:260)
at org.hibernate.internal.util.ReflectHelper.classForName(ReflectHelper.java:193)
at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:2276)
... 5 more
The main class:
package com.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import com.hibernate.data.Person;
public class Main {
public static void main(String [] args){
// Create a configuration instance
Configuration configuration = new Configuration();
// Provide configuration file
configuration.configure("hibernate.cfg.xml");
// Build a SessionFactory
SessionFactory factory = configuration.buildSessionFactory(new StandardServiceRegistryBuilder().configure().build());
// Get current session, current session is already associated with Thread
Session session = factory.getCurrentSession();
// Begin transaction, if you would like save your instances, your calling of save must be associated with a transaction
Transaction tx = session.getTransaction();
// Create person
Person newPerson = new Person();
newPerson.setFirstName("Peter");
newPerson.setLastName("Jackson");
newPerson.setGender("Male");
newPerson.setAge(30);
//Save
session.save(newPerson);
session.flush();
tx.commit();
session.close();
/*
#SuppressWarnings("deprecation")
SessionFactory sf = new Configuration().configure().buildSessionFactory();
System.out.println("CFG and hbm files loaded successfully.");
Session session = sf.openSession();
session.beginTransaction();
System.out.println("Transaction began");
*/
}
}
hbm.xml file:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class table="Person" lazy="false" name="com.hibernate.data.Person" >
<id column="PERSON_ID" type="int" name="id" >
<generator class="increment"/>
</id>
<property name="firstName" column="PERSON_FIRSTNAME" type="string" />
<property name="lastName" column="PERSON_LASTNAME" type="string" />
<property name="gender" column="PERSON_GENDER" type="string" />
<property name="age" column="PERSON_AGE" type="int" />
</class>
hibernate.cfg.xml 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>
<!-- Database connection settings -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/PERSONDB</property>
<property name='connection.username'>root</property>
<property name='connection.password'>root</property>
<!-- SQL dialect -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Specify session context -->
<property name="hibernate.current_session_context_class">thread</property>
<!-- Show SQL -->
<property name="show_sql">true</property>
<!-- Referring Mapping File -->
<mapping resource="domain-classes.hbm.xml"/>
<mapping class="src/main/java/com.hibernate.data/Person"/>
</session-factory>
</hibernate-configuration>
Person.java:
package com.hibernate.data;
public class Person {
private int id;
private String firstName;
private String lastName;
private String gender;
private int age;
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 getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
What is wrong here?
EDIT:
I modified pom.xml file as maven-exec plugin requires:
Additionally, final project structure is as follows:
but still, it gives the same error.What am I doing wrong?
i think:
<mapping class="src/main/java/com.hibernate.data/Person"/>
must be:
<mapping class="com.hibernate.data.Person"/>
also be sure that where is your hbm.xml file?if it is in com package you should write resource like this:
<mapping resource="com/domain-classes.hbm.xml"/>
change
<mapping class="src/main/java/com.hibernate.data/Person"/>
to
<mapping class="com.hibernate.data.Person"/>
I am merely trying to fetch a row of information from the CONTACTS table from my oracle sql database and I get this error :
Caused by: java.sql.SQLSyntaxErrorException: ORA-02289: la séquence n'existe pas (non existing sequence)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:450)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:399)
at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:1017)
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:655)
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:249)
at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:566)
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:215)
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:58)
at oracle.jdbc.driver.T4CPreparedStatement.executeForDescribe(T4CPreparedStatement.java:776)
at oracle.jdbc.driver.OracleStatement.executeMaybeDescribe(OracleStatement.java:897)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1034)
at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3820)
at oracle.jdbc.driver.OraclePreparedStatement.executeQuery(OraclePreparedStatement.java:3867)
at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeQuery(OraclePreparedStatementWrapper.java:1502)
at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeQuery(NewProxyPreparedStatement.java:116)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:80)
... 12 more
Java Result: 1
My Contacts.hbm.xml file :
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Contacts" table="CONTACTS">
<id name="id_contact" type="integer" column="IDCONTACTS">
<generator class="native"/>
</id>
<property name="nom" column="NOM" type="string" length="20"/>
<property name="prenom" column="PRENOM" type="string" length="20"/>
<property name="email" column="EMAIL" type="string" length="20"/>
<property name="salaire" column="SALAIRE" type="integer" length="12"/>
</class>
</hibernate-mapping>
My hibernate.cfg.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.dialect">
org.hibernate.dialect.Oracle10gDialect
</property>
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.url">
adresse...
</property>
<property name="hibernate.connection.username">
login
</property>
<property name="hibernate.connection.password">
psswrd
</property>
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.timeout">300</property>
<property name="hibernate.c3p0.max_statements">50</property>
<property name="hibernate.c3p0.idle_test_period">3000</property>
<mapping class="Contacts" file="" jar="" package="" resource="Contacts.hbm.xml"/>
</session-factory>
</hibernate-configuration>
and Contacts.java
import java.io.Serializable;
public class Contacts implements Serializable {
private int id_contact;
private String nom, prenom, email;
private float salaire;
public Contacts(){
}
public int getId_contact() {
return id_contact;
}
public void setId_contact(int id_contact) {
this.id_contact = id_contact;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public float getSalaire() {
return salaire;
}
public void setSalaire(float salaire) {
this.salaire = salaire;
}
}
The error occurs when I call
session.save(contact1)
//contact1 has been using setters to populate its fields.
And my table on sqlplus look like this
Name Null? Type
----------------------------------------- -------- ----------------------------
IDCONTACT NOT NULL NUMBER(38)
NOM VARCHAR2(20)
PRENOM VARCHAR2(20)
EMAIL VARCHAR2(20)
SALAIRE NUMBER(12)
Thanks for taking a look.
I suppose you've created the table manually (without hibernate).
As you didn't declare the sequence name here
<id name="id_contact" type="integer" column="IDCONTACTS">
<generator class="native"/>
</id>
Hibernate tries to use a sequence named HIBERNATE_SEQUENCE
So you need to create HIBERNATE_SEQUENCE in your DB or define your sequence explicitly:
<id name="id_contact" type="integer" column="IDCONTACTS">
<generator class="native">
<param name="sequence">CONTACTS_SEQ</param>
</generator>
</id>
Hi i am trying to make simple jsp registration form using hibernate where i am getting following Exception
type Exception report
messageInternal Server Error
descriptionThe server encountered an internal error that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: org.hibernate.exception.SQLGrammarException: could not fetch initial value for increment generator
root cause
org.hibernate.exception.SQLGrammarException: could not fetch initial value for increment generator
root cause
com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'index) from user_registration' at line 1
Here is my
Userregistration.hbm.xml
<?xml version='1.0'?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Nov 9, 2011 6:53:58 PM by Hibernate Tools 3.2.1.GA -->
<hibernate-mapping>
<class name="com.hibernateClass.UserRegistration" table="user_registration">
<id name="index">
<generator class="increment"></generator>
</id>
<property name="userName"></property>
<property name="password"></property>
<property name="email"></property>
</class>
</hibernate-mapping>
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">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.url">jdbc:mysql://localhost:3306/employee</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="show_sql">true</property>
<mapping resource="com/hibernateClass/UserRegistration.hbm.xml"/>
</session-factory>
</hibernate-configuration>
UserRegistration.java
public class UserRegistration implements java.io.Serializable {
int index;
String userName;
String password;
String email;
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
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 getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
How can i handle this Exception
and get my desired output
Thanks in advance
maybe 'index' is a keyword .be careful in sql programming , some words look likes keywords ,you should avoid them
Yes we cant use keyword of SQL in code. Otherwise it will show this type of error.
Note: You can check for SQL keyword by write in SQL Editor (Ex. SQLYOG) that will be capital letter ..here is screen Shot.enter image description here
The following code is for insert delete and update data in mysql database table name is student and i created a view using this student table can i perform insert update delete operations on this view if possible suggest me how
This code to retrieve object
package roseindia.tutorial.hibernate;
import org.hibernate.Transaction;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class FirstExam {
public static void main(String[] args)
{
Session session = null;
try{
SessionFactory sessionFactory =newConfiguration().configure().buildSessionFactory();
session =sessionFactory.openSession();
Transaction transacton =session.beginTransaction();
System.out.println("Inserting Record");
Contact contact = new Contact();
//contact.setId(1);
contact.setFirstName("Vikas");
contact.setLastName("Kumar");
contact.setEmail("vikas#gmail.com");
session.save(contact);
//session.update(contact);
//session.delete(contact);
transacton.commit();
System.out.println("Done");
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
finally
{
// Actual contact insertion will happen at this step
session.flush();
session.close();
}
}
}
code for persistence class
package roseindia.tutorial.hibernate;
public class Contact {
private String firstName;
private String lastName;
private String email;
private int id;
public String getEmail() {
return email;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public void setEmail(String string) {
email = string;
}
public void setFirstName(String string) {
firstName = string;
}
public void setLastName(String string) {
lastName = string;
}
public int getId() {
return id;
}
public void setId(int i) {
id = i;
}
}
mapping class
<hibernate-mapping>
<class name="roseindia.tutorial.hibernate.Contact" table="STUDENT">
<id name="id" type="int" column="ID" >
<generator class="increment"/>
</id>
<property name="firstName">
<column name="FIRSTNAME" />
</property>
<property name="lastName">
<column name="LASTNAME"/>
</property>
<property name="email">
<column name="EMAIL"/>
</property>
</class>
</hibernate-mapping>
configuration class
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://192.168.10.161/testdb</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- Mapping files -->
<mapping resource="contact.hbm.xml"/>
</session-factory>
</hibernate-configuration>