auto database creation in hibernate with mysql - java

this is my code, where i done mistake. while running Test.java am getting error like "The requested resource is not available". i kept all this files in same package
hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url"> jdbc:mysql://localhost:3306/studentdb </property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="connection.pool_size"> 1</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hbm2ddl.auto">create</property>
<property name="show_sql">true</property>
<!-- List of XML mapping files -->
<mapping resource="student.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Test.java
public class Test {
public static void main(String[] args) {
Configuration cfg=new Configuration();
cfg.configure("hibernate.cfg.xml");
cfg.buildSessionFactory();
}
}
student.hbm.xml
<hibernate-mapping>
<class name="com.javathub.Student" table="stu_details">
<id name="id">
<generator class="assigned"></generator>
</id>
<property name="name"></property>
<property name="branch"></property>
<property name="fee"></property>
</class>
</hibernate-mapping>
Student.java
public class Student {
private int id;
private String name;
private String branch;
private double fee;
public Student(){
}
public Student(int id, String name, String branch, double fee) {
super();
this.id = id;
this.name = name;
this.branch = branch;
this.fee = fee;
}
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 getBranch() {
return branch;
}
public void setBranch(String branch) {
this.branch = branch;
}
public double getFee() {
return fee;
}
public void setFee(double fee) {
this.fee = fee;
}
}
please help me, thanks in advance

keep the student.hbm.xml and hibernate.cfg.xml in src folder not in package and run again.

Related

Could not determine type for: String, at table: STUDENT, for columns: [org.hibernate.mapping.Column(SNAME)]

how to resolve this exception... please help me...
while I am executing this simple hibernate programme. I am getting this exception :
Exception in thread "main" org.hibernate.MappingException: Could not determine type for: String, at table: STUDENT, for columns: [org.hibernate.mapping.Column(SNAME)]
mapping file:
<?xml version = "1.0" encoding = "utf-8"?>
<hibernate-mapping>
<class name = "Student" table = "STUDENT" >
<meta attribute="Class description">
This contains Student details.
</meta>
<id name="id" type="int" column="id">
<generator class="native"/>
</id>
<property name="name" column="SNAME" type="String"/>
<property name="mNo" column="MNO" type="String"/>
<property name="marks" column="MARKS" type="String"/>
</class>
configuration file:
<?xml version = "1.0" encoding = "utf-8"?>
<hibernate-configuration>
<session-factory>
<!-- <property name="hibernate.dialect">org.hibernate.dialect.MySQLdialect</property> -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/firsthibernate</property>
<property name="hibernate.connection.user">root</property>
<property name="hibernate.connection.password">asdf</property>
<mapping resource="Student.hbm.xml"/>
</session-factory>
Pojo class:
public class Student {
private int id;
private String name;
private String mNo;
private String marks;
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 getmNo() {
return mNo;
}
public void setmNo(String mNo) {
this.mNo = mNo;
}
public String getMarks() {
return marks;
}
public void setMarks(String marks) {
marks = marks;
}
}
Test class:
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class DemoStudent {
public static void main(String[] args) {
Student st=new Student();
st.setId(1);
st.setName("Amit");
st.setmNo("8927070972");
st.setMarks("98%");
Configuration cfg=new Configuration();
cfg.configure();
SessionFactory sf=cfg.buildSessionFactory();
Session s=sf.openSession();
Transaction tr=s.beginTransaction();
tr.begin();
s.save(st);
tr.commit();
}
}
Thanks in advance... while I am executing this simple hibernate programme. I am getting this please help me where I am doing mistake in this programme.
In hibernate mapping file use type as string instead of String.
<property name="name" column="SNAME"
type="string"/>

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;
}
}

Mapping and POJO class creation for a database view in hibernate

Hai all I am using hibernate and Microsoft SQL server.
I have a view in my database as follows
create view [dbo].[Pat_Det] As Select patientid As pid,title, fname, mname,lname,dob,gender,mstatus,idtype,idno,mtongue,emailid,smsstatus,mailstatus,status,regcenter,regdate from dbo.LAB_patientreg WHERE 1=1
For this view I had created a Pojo class like this
package POJO;
import java.io.Serializable;
import java.util.Date;
public class AddressViewPojo implements Serializable{
String pid, title, fname, mname, lname, sex, mstatus, idtype, aadhar_no, emailid, regcenter;
Date dob, date_created;
int allow_sms, allow_email, status;
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getMname() {
return mname;
}
public void setMname(String mname) {
this.mname = mname;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getMstatus() {
return mstatus;
}
public void setMstatus(String mstatus) {
this.mstatus = mstatus;
}
public String getIdtype() {
return idtype;
}
public void setIdtype(String idtype) {
this.idtype = idtype;
}
public String getAadhar_no() {
return aadhar_no;
}
public void setAadhar_no(String aadhar_no) {
this.aadhar_no = aadhar_no;
}
public String getEmailid() {
return emailid;
}
public void setEmailid(String emailid) {
this.emailid = emailid;
}
public String getRegcenter() {
return regcenter;
}
public void setRegcenter(String regcenter) {
this.regcenter = regcenter;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public Date getDate_created() {
return date_created;
}
public void setDate_created(Date date_created) {
this.date_created = date_created;
}
public int getAllow_sms() {
return allow_sms;
}
public void setAllow_sms(int allow_sms) {
this.allow_sms = allow_sms;
}
public int getAllow_email() {
return allow_email;
}
public void setAllow_email(int allow_email) {
this.allow_email = allow_email;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
}
and Mapping file like this
<?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 auto-import="true" default-lazy="false">
<class name="POJO.AddressViewPojo" table="Pat_Det">
<property name="aadhar_no" column="aadhar_no"></property>
<property name="allow_email" column="allow_email"></property>
<property name="allow_sms" column="allow_sms"></property>
<property name="date_created" column="date_created"></property>
<property name="dob" column="dob"></property>
<property name="emailid" column="emailid"></property>
<property name="fname" column="emailid"></property>
<property name="idtype" column="idtype"></property>
<property name="lname" column="lname"></property>
<property name="mname" column="mname"></property>
<property name="mstatus" column="mstatus"></property>
<property name="pid" column="pid"></property>
<property name="regcenter" column="regcenter"></property>
<property name="sex" column="sex"></property>
<property name="status" column="status"></property>
<property name="title" column="title"></property>
</class>
</hibernate-mapping>
But when I am validating the Mapping file an error occurs like this
XML validation started.
Checking file:/E:/akshai/TREVALAB/src/MAPPING/AddressViewPojo.hbm.xml...
The content of element type "class" must match "(meta*,subselect?,cache?,synchronize*,comment?,tuplizer*,(id|composite-id),discriminator?,natural-id?,(version|timestamp)?,(property|many-to-one|one-to-one|component|dynamic-component|properties|any|map|set|list|bag|idbag|array|primitive-array)*,((join*,subclass*)|joined-subclass*|union-subclass*),loader?,sql-insert?,sql-update?,sql-delete?,filter*,resultset*,(query|sql-query)*)". [21]
XML validation finished.
Can anyone help me to solve out this issue.
Thanks in advance.
Your mapping absolutely needs an id. I guess PID is your id so you should write something like this :
<?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 auto-import="true" default-lazy="false">
<class name="POJO.AddressViewPojo" table="Pat_Det">
<id name="pid" column="pid"></id> <!-- Right here -->
<property name="aadhar_no" column="aadhar_no"></property>
<property name="allow_email" column="allow_email"></property>
<property name="allow_sms" column="allow_sms"></property>
<property name="date_created" column="date_created"></property>
<property name="dob" column="dob"></property>
<property name="emailid" column="emailid"></property>
<property name="fname" column="emailid"></property>
<property name="idtype" column="idtype"></property>
<property name="lname" column="lname"></property>
<property name="mname" column="mname"></property>
<property name="mstatus" column="mstatus"></property>
<property name="regcenter" column="regcenter"></property>
<property name="sex" column="sex"></property>
<property name="status" column="status"></property>
<property name="title" column="title"></property>
</class>
</hibernate-mapping>

Exception in thread "main" org.hibernate.MappingException: invalid configuration

Hi Iam trying to run my hiberanate application i am getting the Hibernate Exception.
my hibernate.cfg.xml file is
<?xml version='1.0' encoding='UTF-8'?>
<session-factory>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect </property>
<property name="connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="connection.username">root</property>
<property name="connection.password">mysql</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- <mapping resource="config\\hibernate.hbm.xml"/ -->
<mapping resource="config\\employee.hbm.xml"/>>
</session-factory>
employee.hbm.xml
<?xml version='1.0' encoding='UTF-8'?>
<hibernate-mapping>
<class name = "com.javatpoint.mypackage.Employee" table = "emp_TPCH" discriminator-value="emp">
<id name = "id">
<generator class = "increment">
</generator>
</id>
<discriminator column="type" type= "string"></discriminator>
<property name ="Name"></property>
<subclass name = "com.javatpoint.mypackage.Regular_Employee" discriminator-value="reg_emp">
<property name = "salary"></property>
<property name = "bonus"></property>
</subclass>
<subclass name = "com.javatpoint.mypackage.Contract_Employee" discriminator-value = "con_emp">
<property name = "pay_Per_Hour"></property>
<property name = "contact_Duration"></property>
</subclass>
</class>
</hibernate-mapping>
Employee.java is
package com.javatpoint.mpackage;
public class Employee {
private int id;
private String name;
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;
}
}
Contract_Employee.java
package com.javatpoint.mpackage;
public class Contract_Employee extends Employee {
private float pay_Per_Hour;
private String contact_Duration;
public float getPay_Per_Hour() {
return pay_Per_Hour;
}
public void setPay_Per_Hour(float pay_Per_Hour) {
this.pay_Per_Hour = pay_Per_Hour;
}
public String getContact_Duration() {
return contact_Duration;
}
public void setContact_Duration(String contact_Duration) {
this.contact_Duration = contact_Duration;
}
}
Regular Employee.js is
package com.javatpoint.mpackage;
public class Regular_Employee extends Employee {
private float salary;
private int bonus;
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
public int getBonus() {
return bonus;
}
public void setBonus(int bonus) {
this.bonus = bonus;
}
}
Guys please help me to come out of this Exception.
Include this as the second line in your file:
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
There are maybe other errors, but this line is invalid:
<mapping resource="config\\employee.hbm.xml"/>>
^-- two brackets here
Also, the resource should be config/employee.hbm.xml. The resource is a classpath resource, using forward slashes as path separator.

Exception in thread "main" org.hibernate.InvalidMappingException: Could not parse mapping document from resource employee.hbm.xml

Hi I am getting the exception :
Exception in thread "main" org.hibernate.InvalidMappingException: Could not parse mapping document from resource employee.hbm.xml
employee.hbm.xml is:
here is the tablepersubclass Hierarchy configuration file:
<hibernate-mapping package = "com.javatpoint.mypackage">
<class name = "Employee" table = "Employee">
<id name = "id" column = "eid">
<generator class = "increment"></generator>
</id>
<property name = "name" column = "name"></property>
<joined-subclass name = "Regular_Employee" table = "RegEmployee">
<key column = "eid"></key>
<property name = "salary" column = "salary"></property>
<property name = bonus column = "bonus"> </property>
</joined-subclass>
<joined-subclass name = "Contract_Emloyee" table = "ConEmployee">
<key column = "eid"> </key>
<property name = "pay_per_hour" name = "pay_per_hour"></property>
<property name = "contract_duration" name = "contract_duration"></property>
</joined-subclass>
</class>
</hibernate-mapping>
and the configuration file hibernate.cfg.xml file is:
<session-factory>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect </property>
<property name="connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="connection.username">root</property>
<property name="connection.password">mysql</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<mapping resource="employee.hbm.xml"/>
</session-factory>
Employee.java is:
package com.javatpoint.mypackage;
public class Employee {
private int id;
private String name;
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;
}
}
Contract_Employee.java is:
package com.javatpoint.mypackage;
public class Contract_Emloyee extends Employee{
private float pay_per_hour;
private String contract_duration;
public float getPay_per_hour() {
return pay_per_hour;
}
public void setPay_per_hour(float pay_per_hour) {
this.pay_per_hour = pay_per_hour;
}
public String getContract_duration() {
return contract_duration;
}
public void setContract_duration(String contract_duration) {
this.contract_duration = contract_duration;
}
}
Regular_Employee.java is :
package com.javatpoint.mypackage;
public class Regular_Employee extends Employee{
private float salary;
private int bonus;
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
public int getBonus() {
return bonus;
}
public void setBonus(int bonus) {
this.bonus = bonus;
}
}
Your employee.hbm.xml is invalid xml.
<property name= bonus column="bonus"></property>
Change that to this:
<property name="bonus" column="bonus"></property>

Categories