Can not established a connection to jdbc with Hibernate-SQL Server 2008 - java

I made a connection to SQL server with Hibernate configuration wizard, when I click test connection, I get success message, but when I want to make hibernate mapping, I cannot I get error message, Cannot established a connection to jdbc. The below code is jdbc connection with hibernate; please say me, what is the problem?
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="hibernate.connection.url">jdbc:sqlserver://localhost; databaseName=Test</property>
<property name="hibernate.connection.username">sa</property>
<property name="hibernate.connection.password">sa123</property>
<property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
</session-factory>
</hibernate-configuration>
Best Regards

After looking into your code i found you did not specify the port number for database connection
<property name="hibernate.connection.url">jdbc:sqlserver://localhost; databaseName=Test</property>
There should be a port number if your trying to connect on your local machine for an example please refer following line
<property name="hibernate.connection.url">jdbc:sqlserver://localhost:1433;DatabaseName=syv</property>
Please check and let me know ...if there is any further issue
Ok here i am sending you the basic hibernate configuration : -
STEP 1 :- *Create a Java File “AddStudent” and paste the below code into that.*
//package code;
import java.sql.*;
import java.io.*;
import org.hibernate.*;
import org.hibernate.cfg.*;
public class AddStudent {
private static SessionFactory sessionFactory;
public static void main(String args[]) throws Exception {
DataInputStream d = new DataInputStream(System.in);
System.out.println("ENTER YOUR NAME");
String name = d.readLine();
System.out.println("ENTER YOUR DEGREE");
String degree = d.readLine();
System.out.println("ENTER YOUR PHONE");
String phone = d.readLine();
System.out.println("Name: " + name);
System.out.println("Degree: " + degree);
System.out.println("Phone: " + phone);
if ((name.equals("") || degree.equals("") || phone.equals(""))) {
System.out.println("All informations are Required");
} else {
try {
// begin try
sessionFactory = new Configuration().configure()
.buildSessionFactory();
} catch (Exception e) {
System.out.println(e.getMessage());
System.err.println("Initial SessionFactory creation failed."
+ e);
}
Session s = sessionFactory.openSession();
Transaction tx = s.beginTransaction();
Student stu = new Student();
stu.setName(name);
stu.setDegree(degree);
stu.setPhone(phone);
s.save(stu);
tx.commit();
System.out.println("Added to Database");
if (s != null)
s.close();
}
}
}
STEP 2 : Create a Java File “Student” paste the below code into that.
//package code;
import java.io.*;
public class Student implements Serializable {
private long id;
private String name;
private String degree;
private String phone;
public long getId() {
return id;
}
public String getName() {
return name;
}
public String getDegree() {
return degree;
}
public String getPhone() {
return phone;
}
public void setId(long string) {
id = string;
}
public void setName(String string) {
name = string;
}
public void setDegree(String string) {
degree = string;
}
public void setPhone(String string) {
phone = string;
}
public String toString() {
return name;
}
}
Step 3: Create an xml file “hibernate.cfg.xml” place the below code into that.
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory name="studentFactory">
<property name="connection.driver_class">
oracle.jdbc.OracleDriver
</property>
<property name="connection.url">
jdbc:oracle:thin:#localhost:1521:XE
</property>
<property name="connection.username">
system
</property>
<property name="connection.password">
system
</property>
<property name="connection.pool_size">5</property>
<!-- SQL dialect -->
<property name="dialect">
org.hibernate.dialect.OracleDialect
</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">false</property>
<mapping resource="Student.hbm.xml" />
</session-factory>
</hibernate-configuration>
Step 4:Create an xml File “student.hbm.xml” and place below code into that.
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping >
<class name="Student" table="Stutbl" >
<id name="id" type="long" column ="ID">
<generator class="increment"/>
</id>
<property name="name" column="name" not-null="true"/>
<property name="degree" column="degree" />
<property name="phone" column="phone" />
</class>
</hibernate-mapping>
Step 5: Add the required jar to your project
Hope it will solve your problem

Add this:
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.SQLServerDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
and verify if your Database accept connections.

Related

Hibernate + SQLite do not create tables

I need SQLite database in my project, but SQL is not as handy as HQL. So we have Hibernate with SQLite.
Project is being made in NetBeans 8.2, my OS is Ubuntu 17.10.
So for example we have this mini-project for testing
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">org.sqlite.JDBC</property>
<property name="hibernate.connection.url">jdbc:sqlite:stuff.db</property>
<property name="hibernate.dialect">com.enigmabridge.hibernate.dialect.SQLiteDialect</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<property name="hibernate.show_sql">true</property>
<mapping resource="stuff/Stuff.hbm.xml"/>
</session-factory>
</hibernate-configuration>
My class called Stuff:
package stuff;
public class Stuff {
private Integer id;
private String stuff;
public Stuff() {
}
public Stuff(String stuff) {
this.stuff = stuff;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getStuff() {
return stuff;
}
public void setStuff(String stuff) {
this.stuff = stuff;
}
#Override
public String toString() {
return "Stuff{" + "id=" + id + ", stuff=" + stuff + '}';
}
}
Mapping file
<hibernate-mapping>
<class name="stuff.Stuff" table="stuff">
<id name="id" type="integer" column="id">
<generator class="increment"/>
</id>
<property name="stuff" type="string" column="stuff"/>
</class>
</hibernate-mapping>
And the main code
package stuff;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
public class Main {
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
session.save(new Stuff("blah blah"));
//Query q = s.createQuery("select from Stuff");
//List<Stuff> l = q.list();
//for (Stuff s:l)System.out.println(s);
session.getTransaction().commit();
session.close();
System.exit(0);
}
}
Data base was created via Services tab in NetBeans. Its name is stuff.db.
I use Hibernate 4.3 (JPA 2.1)
Hibernate 4 SQLite dialect was taken from here: link
Session opens and closes just fine, database file is automatically created in my home folder. But for some reason table just isn't created, I really dunno why.
pom: SQLite JDBC library
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.7.2</version>
</dependency>
in hibernate config:
<?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="show_sql">true</property>
<property name="format_sql">true</property>
<property name="dialect">org.hibernate.dialect.SQLiteDialect</property>
<property name="connection.driver_class">org.sqlite.JDBC</property>
<property name="connection.url">jdbc:sqlite:mydb.db</property>
<property name="connection.username"></property>
<property name="connection.password"></property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping class="your mapping class"/>
</session-factory>
</hibernate-configuration>

Hibernate postgres - relation "userdetails" does not exist

I'm just starting with hibernate and I have a simple configuration that gives me this error: "relation "userdetails" does not exist" when I try to first save the only class I have.
my hibernate.gfg.xml file:
<!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">org.postgresql.Driver</property>
<property name="hibernate.connection.username">postgres</property>
<property name="hibernate.connection.password">XXXX</property>
<property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/hibernatedb</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">
org.hibernate.dialect.PostgreSQLDialect
</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="show_sql">true</property>
<property name="hdm2ddl.auto">create</property>
<mapping class="hibernate.project.UserDetails"/>
</session-factory>
</hibernate-configuration>
my only model class:
#Entity
public class UserDetails {
#Id
private int userId;
private String userName;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
my main:
public static void main(String[] args) {
UserDetails user = new UserDetails();
user.setUserId(1);
user.setUserName("First User");
Configuration config = new Configuration().configure();
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(config.getProperties()).build();
SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);
Session session=sessionFactory.openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
}
any ideas? I've found similar questions but didn't help. thanks!
The create property is incorrect : Use hbm2ddl instead of hdm2ddl
<property name="hibernate.hbm2ddl.auto">create</property>
OR
<property name="hbm2ddl.auto">create</property>
and not
hdm2ddl.auto
Seems to be typo at your end.

Hibernate - Restriction between()

Criteria cr=session.createCriteria(Student.class).add(Restrictions.between("strStudentMark1", "90", "100"));
In the above code snippet, I have given the mark between 90 and 100. In the Student table, there are fields between marks 90 and 100. but am not getting those in the output.
What could be the problem? Am I making any mistake?
EDIT
Yes am getting the whole list when I run.
Criteria cr=session.createCriteria(Student.class);
Student entity is below with generated Getters and Setters.
import java.io.Serializable;
public class Student implements Serializable {
private String strStudentID;
private String strStudentRegNO;
private String strStudentName;
private String strStudentMark1;
private String strStudentMark2;
private String strStudentDegree;
private String strStudentMobileNO;
private String strStudentMailID;
private String strSalary;
public String getStrSalary() {
return strSalary;
}
public void setStrSalary(String strSalary) {
this.strSalary = strSalary;
}
public String getStrStudentID() {
return strStudentID;
}
public void setStrStudentID(String strStudentID) {
this.strStudentID = strStudentID;
}
public String getStrStudentRegNO() {
return strStudentRegNO;
}
public void setStrStudentRegNO(String strStudentRegNO) {
this.strStudentRegNO = strStudentRegNO;
}
public String getStrStudentName() {
return strStudentName;
}
public void setStrStudentName(String strStudentName) {
this.strStudentName = strStudentName;
}
public String getStrStudentMark1() {
return strStudentMark1;
}
public void setStrStudentMark1(String strStudentMark1) {
this.strStudentMark1 = strStudentMark1;
}
public String getStrStudentMark2() {
return strStudentMark2;
}
public void setStrStudentMark2(String strStudentMark2) {
this.strStudentMark2 = strStudentMark2;
}
public String getStrStudentDegree() {
return strStudentDegree;
}
public void setStrStudentDegree(String strStudentDegree) {
this.strStudentDegree = strStudentDegree;
}
public String getStrStudentMobileNO() {
return strStudentMobileNO;
}
public void setStrStudentMobileNO(String strStudentMobileNO) {
this.strStudentMobileNO = strStudentMobileNO;
}
public String getStrStudentMailID() {
return strStudentMailID;
}
public void setStrStudentMailID(String strStudentMailID) {
this.strStudentMailID = strStudentMailID;
}
}
hibernate.cfg.xml.
<!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">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:#aaaa:bbbb</property>
<property name="connection.username">xxx</property>
<property name="connection.password">yyy</property>
<!-- <property name="connection.pool_size">5</property> -->
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<property name="current_session_context_class">thread</property>
<!-- <property name="hbm2ddl.auto">update</property> -->
<mapping resource="com/hibresources/Student.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Student.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 17 Dec, 2010 5:54:42 AM by Hibernate Tools 3.3.0.GA -->
<hibernate-mapping>
<class name="com.bean.Student" table="STUDENT">
<meta attribute="class-description">
This class has details abt Students
</meta>
<id name="strStudentID" >
<column name="STUID" />
</id>
<property name="strStudentRegNO" >
<column name="STUREG_NO" />
</property>
<property name="strStudentName" >
<column name="STUNAME" />
</property>
<property name="strStudentMark1" >
<column name="STUMARK1" />
</property>
<property name="strStudentMark2" >
<column name="STUMARK2" />
</property>
<property name="strStudentDegree" >
<column name="DEGREE" />
</property>
<property name="strStudentMobileNO" >
<column name="MOBILENO" />
</property>
<property name="strStudentMailID" >
<column name="MAILID" />
</property>
<property name="strSalary" >
<column name="SALARY" />
</property>
</class>
</hibernate-mapping>
Please make sure that the data stored in the Database is an INT. The between will only work with INT Datatype. Also try passing the value as int in code.

how to resolve ==> org.hibernate.exception.GenericJDBCException: Could not open connection

when i execute my Main class i get this execution
cant figure out the issue point
the error comes in the line
Transaction tr = session.beginTransaction();
error stack says :
ERROR: Access denied for user 'root'#'localhost' (using password: NO)
error===>org.hibernate.exception.GenericJDBCException: Could not open connection
my Main class File :
package com.hussi.model;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class Main {
public static void main(String[] args)
{
User user = new User();
user.setUser_id(1);
user.setUsername("hussi");
user.setPassword("maria");
SessionFactory sesionFactory = new Configuration().configure().buildSessionFactory() ;
Session session = sesionFactory.openSession();
try{
Transaction tr = session.beginTransaction();
session.save(user);
}
catch(Exception e)
{
System.out.println("error===>"+e);
}
finally
{
session.flush();
session.close();
}
}
}
my model file
package com.hussi.model;
public class User
{
int user_id;
String username;
String password;
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
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 toString()
{
return "username==>"+this.username+" : password==>"+this.password;
}
}
my user.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 name="com.hussi.model.User" table="users">
<id name="user_id" type="int" column="user_id">
<generator class="increment" />
</id>
<property name="username">
<column name="username"/>
</property>
<property name="password">
<column name="password"/>
</property>
</class>
</hibernate-mapping>
my hibernate configuration file : 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>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/my_hibernate_1</property>
<property name="connection.username">root</property>
<property name="connecttion.password">root</property>
<!-- Database connection settings -->
<property name="connection.pool_size">1</property>
<!-- MySql Dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">false</property>
<mapping resource="user.hbm.xml"/>
</session-factory>
</hibernate-configuration>
I believe you need to reset your database password. Follow this link to do the same:
http://dev.mysql.com/doc/refman/5.1/en/resetting-permissions.html
or the user priviliges are not correct. Follow this to set priviliges:
http://dev.mysql.com/doc/refman/5.1/en/default-privileges.html

Could not parse mapping document error in hibernate

This is my first post in stackoverflow:
I am new to hibernate, infact below is my first code in hibernate:
i am repetedly getting "could not parse mapping document" error, when i run my main class.
below is the code for your refernce, please help me out of this.
Config 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.DerbyDialect</property>
<property name="hibernate.connection.driver_class">org.apache.derby.jdbc.ClientDriver</property>
<property name="hibernate.connection.url">jdbc:derby://localhost:1527/sample</property>
<property name="hibernate.connection.username">one</property>
<property name="hibernate.connection.password">two</property>
<property name="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
<property name="hibernate.current_session_context_class">thread</property>
<mapping resource="EmployeeMapping.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Mapping 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="Employee" table="EMPLOYEE"/>
<id name="emp_id" type="int" column="emp_id"/>
<property name="emp_name">
<column name="emp_name"/>
</property>
<property name="emp_branch">
<column name="emp_branch"/>
</property>
<property name="emp_Salary">
<column name="emp_salary"/>
</property>
<property name="emp_fav_dgt">
<column name="emp_fav_dgt"/>
</property>
</hibernate-mapping>
Pojo class:
public class Employee {
private int emp_id;
private String emp_name;
private String emp_branch;
private int emp_Salary;
private int emp_fav_dgt;
public int getEmp_Salary() {
return emp_Salary;
}
public void setEmp_Salary(int emp_Salary) {
this.emp_Salary = emp_Salary;
}
public String getEmp_branch() {
return emp_branch;
}
public void setEmp_branch(String emp_branch) {
this.emp_branch = emp_branch;
}
public int getEmp_fav_dgt() {
return emp_fav_dgt;
}
public void setEmp_fav_dgt(int emp_fav_dgt) {
this.emp_fav_dgt = emp_fav_dgt;
}
public int getEmp_id() {
return emp_id;
}
public void setEmp_id(int emp_id) {
this.emp_id = emp_id;
}
public String getEmp_name() {
return emp_name;
}
public void setEmp_name(String emp_name) {
this.emp_name = emp_name;
}
}
Main class:
public class Main {
public static void main(String[] args) {
System.out.println("asdf");
SessionFactory sessionFactory = null;
Transaction ts = null;
Session session = null;
Configuration conf = null;
try{
conf = new org.hibernate.cfg.Configuration().configure();
sessionFactory = conf.buildSessionFactory();
session =sessionFactory.openSession();
Employee customer = new Employee();
customer.setEmp_id(1);
customer.setEmp_name("one");
customer.setEmp_branch("old");
customer.setEmp_Salary(1000);
customer.setEmp_fav_dgt(2);
session.save(customer);
ts.commit();
}
catch(Exception e){
e.printStackTrace();;
}
finally{
session.close();
}
}
}
The property tags corresponding with the fields should be nested within the class tag.
<class name="Employee" table="EMPLOYEE">
<id name="emp_id" type="int" column="emp_id"/>
<property name="emp_name">
<column name="emp_name"/>
</property>
<property name="emp_branch">
<column name="emp_branch"/>
</property>
<property name="emp_Salary">
<column name="emp_salary"/>
</property>
<property name="emp_fav_dgt">
<column name="emp_fav_dgt"/>
</property>
</class>

Categories