I am using "select max(pid) from Patient p" in hibernate using spring mvc framework and it is showing "Stacktrace:] with root cause
org.hibernate.hql.internal.ast.QuerySyntaxException: Patient is not mapped" and lots more error. Why???
<%
Configuration cfg = new Configuration();
cfg.configure("doc.cfg.xml");
SessionFactory sf = cfg.buildSessionFactory();
Session s = sf.openSession();
Query q = s.createQuery("select max(pid) from Patient p");
List lst = q.list();
%>
Actually I want the value
<%=lst %>
and want to get the max of pid from my POJO class Patient from the database patient having pid as integer values.
patient.java
package dao;
public class patient {
private String ppass , pname , mob , age , sex , addr;
private int pid;
public String getPpass() {
return ppass;
}
public void setPpass(String ppass) {
this.ppass = ppass;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public String getMob() {
return mob;
}
public void setMob(String mob) {
this.mob = mob;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
}
and
doc.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="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name=
"connection.url">jdbc:mysql://localhost:3306/doctoapp</property>
<property name="connection.username">root</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hbm2ddl.auto">update</property>
<property name="show_sql">true</property>
<!-- student class ka mapping -->
<mapping resource="doc.hbm.xml"/>
<mapping resource="pat.hbm.xml"/>
</session-factory>
</hibernate-configuration>
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.
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.
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;
}
}
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>
I need to do Inner join between two tables, but without success, I have to find all the patients related to a particular User,I tried to query without success.
I am using mysql and hibernate 3.6.4.
This is my code
Patient.java
#Entity
public class Patient {
#Id
private int id;
private String paitentFirstName;
private String paitentLastName;
private Date dateOfbirth;
private String sex;
#ManyToMany(cascade = {CascadeType.ALL})
#JoinTable(name="User_Patient",
joinColumns={#JoinColumn(name="id")},
inverseJoinColumns={#JoinColumn(name="userName")})
private Set<User> users = new HashSet<User>();
public Set<User> getUsers() {
return users;
}
public void setMeetings(Set<User> users) {
this.users = users;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPaitentFirstName() {
return paitentFirstName;
}
public void setPaitentFirstName(String paitentFirstName) {
this.paitentFirstName = paitentFirstName;
}
public String getPaitentLastName() {
return paitentLastName;
}
public void setPaitentLastName(String paitentLastName) {
this.paitentLastName = paitentLastName;
}
public Date getDateOfbirth() {
return dateOfbirth;
}
public void setDateOfbirth(Date dateOfbirth) {
this.dateOfbirth = dateOfbirth;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
#Override
public String toString() {
return "Patient [id=" + id + ", paitentFirstName=" + paitentFirstName
+ ", paitentLastName=" + paitentLastName + ", dateOfbirth="
+ dateOfbirth + ", sex=" + sex + "]";
}
}
User.java
#Entity
public class User {
#Id
private String UserName;
#ManyToMany(mappedBy="users")
private Set<Patient> patients = new HashSet<Patient>();
public String getUserName() {
return UserName;
}
public void setUserName(String userName) {
UserName = userName;
}
public Set<Patient> getEmployees() {
return patients;
}
public void setEmployees(Set<Patient> patients) {
this.patients = patients;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
private String password;
}
Hibernate configuration 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="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/test2</property>
<property name="connection.username">root</property>
<property name="connection.password">1234</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
<!-- Names the annotated entity class -->
<mapping class="com.objects.Patient"/>
<mapping class="com.objects.User"/>
</session-factory>
</hibernate-configuration>
There is no need for explicit join.
With Hibernate version that do have HHH-5209 fixed, query can be written as follows:
SELECT p
FROM Patient p
WHERE :particularUser MEMBER OF p.users
With older versions IN ELEMENTS can be used instead:
SELECT p
FROM Patient p
WHERE :particularUser IN ELEMENTS (p.users)