hibernate调用存储过程,一个简单使用
分类:面向对象

一、建表

 

1、  下载hibernate-release-4.1.8.Final.zip包

前几天始发用Nhibernate做为本人的ORM,不过做的进程中的确遇见了成千上万标题,未来将难题搜聚起来幸免日后现身相近的主题材料,

DROP TABLE IF EXISTS `user`;

在此以前创立 MySQL数据库代码如下: create database if not exists `myproject`;
USE `myproject`;
DROP TABLE IF EXISTS `myusertable`;
CREATE TABLE `myusertable` (           
               `ID` int(8) NOT NULL auto_increment,
               `UserName` varchar(16) default NULL,
               `Password` varchar(16) default NULL,
               `Email` varchar(32) default NULL,    
               PRIMARY KEY (`ID`)                  
             ) ENGINE=InnoDB DEFAULT CHARSET=gbk  

总结下:

CREATE TABLE `user` (

创设可漫长化类,User.java(卡塔尔(قطر‎类: package ch03.hibernate;

2、  部署

图片 1

   `ID` int(11) NOT NULL auto_increment,

public class User {
private int id;
private String username;
private String password;
private String email;
public String getEmail() {
   return email;
}
public void setEmail(String email) {
   this.email = email;
}
public int getId() {
   return id;
}
public void setId(int id) {
   this.id = id;
}
public String getPassword() {
   return password;
}
public void setPassword(String password) {
   this.password = password;
}
public String getUsername() {
   return username;
}
public void setUsername(String username) {
   this.username = username;
}
}

将lib下required文件夹下的持有jar包复制到WEB-INFlib目录下

那正是本身的成套项目,以后布局下hibernate.cfg.xml

   `NAME` varchar(16) NOT NULL default '',

成立布局文件,hibernate.cfg.xm文件l: <?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "">

在src下开创hibernate.cfg.xml配置文件

<?xml version="1.0" encoding="utf-8"?>
<!--
This template was written to work with NHibernate.Test.
Copy the template to your NHibernate.Test project folder and rename it in hibernate.cfg.xml and change it

   `REMARK` varchar(16) NOT NULL default '',

<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

hibernate.cfg.xml

for your own use before compile tests in VisualStudio.
-->
<!-- This is the System.Data.dll provider for SQL Server -->
<hibernate-configuration  xmlns="urn:nhibernate-configuration-2.2" >
    <session-factory name="NHibernate.Test">
        <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
        <property name="connection.connection_string">
      server=127.0.0.1;database=Subject;uid=sa;pwd=zhangwei
    </property>
        <property name="dialect">NHibernate.Dialect.MsSql2008Dialect</property>
  </session-factory>
</hibernate-configuration>

   PRIMARY KEY (`ID`)

<session-factory>
   <property name="dialect">
    org.hibernate.dialect.MySQLDialect
   </property>
   <property name="connection.url">
    jdbc:mysql://localhost:3306/myproject
   </property>
   <property name="connection.username">root</property>
   <property name="connection.password">root</property>
   <property name="connection.driver_class">
    com.mysql.jdbc.Driver
   </property>
   <property name="myeclipse.connection.profile">MySQL</property>
   <mapping resource="ch03/hibernate/Myusertable.hbm.xml" />

复制代码
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE hibernate-configuration PUBLIC
 3     "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
 4     ";
 5 
 6 <hibernate-configuration>
 7        <session-factory>
 8        
 9         <!-- 数据库驱动名称 -->
10         <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
11         <!-- 数据库链接地址 -->
12         <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate</property>
13         <!-- 数据库客商名称 -->
14         <property name="hibernate.connection.username">root</property>
15         <!-- 数据库密码 -->
16         <property name="connection.password">admin</property>
17         <!-- 设置数据库连接池默许个数 -->
18         <property name="connection.pool_size">1</property>
19         <!-- 设置数据库SQL语言类型 -->
20         <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
21         <!-- 设置是或不是出示SQL语句-->
22         <property name="show_sql">true</property>
23         <!-- 设置是不是格式化SQL语句 -->
24         <property name="format_sql">true</property>
25         <!-- 设置使用线程-->
26         <property name="current_session_context_class">thread</property>
27         <!-- 设置hibernate的光彩夺目文件-->
28         <mapping  resource="edu/dzu/vo/UsersVo.hbm.xml"/>
29         
30     </session-factory>
31 </hibernate-configuration>
复制代码
3、  应用

 

) ENGINE=InnoDB AUTO_INCREMENT=24 DEFAULT CHARSET=utf8;

</session-factory>
</hibernate-configuration>

创造数据库,数据库名hibernate

现行反革命新建User.cs类:

二、创立存款和储蓄进度

创制映射文件,User.hbm.xml文件: <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"">
<!--
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
    <class name="ch03.hibernate.User" table="myusertable" catalog="myproject">
        <id name="id" type="java.lang.Integer">
            <column name="ID" />
            <generator class="assigned" />
        </id>
        <property name="username" type="java.lang.String">
            <column name="UserName" length="16" />
        </property>
        <property name="password" type="java.lang.String">
            <column name="Password" length="16" />
        </property>
        <property name="email" type="java.lang.String">
            <column name="Email" length="32" />
        </property>
    </class>
</hibernate-mapping>

复制代码
 1 -- ----------------------------
 2 -- Table structure for `users`
 3 -- ----------------------------
 4 DROP TABLE IF EXISTS `users`;
 5 CREATE TABLE `users` (
 6   `id` int(11) NOT NULL,
 7   `name` varchar(20) DEFAULT NULL,
 8   `age` int(11) DEFAULT NULL,
 9   `tel` varchar(20) DEFAULT NULL,
10   `address` varchar(50) DEFAULT NULL,
11   PRIMARY KEY (`id`)
12 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
复制代码
edu.dzu.vo包中

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

1、获取客商新闻

树立测量试验类,Test.java类: package ch03.hibernate;

UsersVo.hbm.xml

namespace Subject.Model
{
    /// <summary>
    /// 用户表
    /// </summary>
    public class User
    {
        /// <summary>
        /// 用户id
        /// </summary>
        public string Id { get; set; }

CREATE DEFINER=`root`@`localhost` PROCEDURE `getUserList`()

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

复制代码
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE hibernate-mapping PUBLIC
 3     "-//Hibernate/Hibernate Hibernate-mapping DTD 3.0//EN"
 4     ";
 5 
 6 <hibernate-mapping>
 7     
 8     <class name="edu.dzu.vo.Users" table="users" catalog="hibernate"> 
 9         
10         <id name="id" type="java.lang.Integer">
11             <column name="id"></column>
12             <generator class="assigned"></generator>
13         </id>
14         
15         <property name="name" type="java.lang.String">
16             <column name="name" length="20"></column>
17         </property>
18         
19         <property name="age" type="java.lang.Integer">
20             <column name="age"></column>
21         </property>
22         
23         <property name="tel" type="java.lang.String">
24             <column name="tel" length="20"></column>
25         </property>
26         
27         <property name="address" type="java.lang.String">
28             <column name="address" length="50"></column>
29         </property>
30         
31     </class>
32     
33 </hibernate-mapping>
复制代码
Users.java

        /// <summary>
        /// 名称
        /// </summary>
        public string Name { get; set; }

BEGIN

public class Test {

复制代码
 1 package edu.dzu.vo;
 2 
 3 import java.io.Serializable;
 4 
 5 public class Users implements Serializable {
 6 
 7     /**
 8      * 
 9      */
10     private static final long serialVersionUID = 1L;
11 
12     private Integer id;
13     private String name;
14     private Integer age;
15     private String tel;
16     private String address;
17     
18     public Users(){
19         
20     }
21     
22     public Users(Integer id){
23         this.id = id;
24     }
25     
26     public Users(Integer id, String name, 
27             Integer age, String tel, String address){
28         this.id = id;
29         this.name = name;
30         this.age = age;
31         this.tel = tel;
32         this.address = address;
33     }
34     
35     public int getId() {
36         return id;
37     }
38     public void setId(int id) {
39         this.id = id;
40     }
41     public String getName() {
42         return name;
43     }
44     public void setName(String name) {
45         this.name = name;
46     }
47     public int getAge() {
48         return age;
49     }
50     public void setAge(int age) {
51         this.age = age;
52     }
53     public String getTel() {
54         return tel;
55     }
56     public void setTel(String tel) {
57         this.tel = tel;
58     }
59     public String getAddress() {
60         return address;
61     }
62     public void setAddress(String address) {
63         this.address = address;
64     }
65     
66 }
复制代码
HibernateSessionFactory.java

        /// <summary>
        /// 密码
        /// </summary>
        public string Password { get; set; }

   select * from user;

public static void main(String[] args) {

复制代码
package edu.dzu.vo;

        /// <summary>
        /// 性别
        /// </summary>
        public string Sex { get; set; }

END;

   try
   {
    SessionFactory sf = new Configuration().configure().buildSessionFactory();
  
    Session session = sf.openSession();

import org.hibernate.*;
import org.hibernate.cfg.Configuration;

        /// <summary>
        /// 个人简单介绍
        /// </summary>
        public string BriefIntroduction { get; set; }

2、通过传播参数成立顾客

    Transaction tx = session.beginTransaction();
    User user = new User();
    user.setUsername("HuSuMioa");
    user.setPassword("12345");
   
    session.save(user);
   
    tx.commit();
    session.close();
  
   }
   catch(HibernateException err)
   {
    err.printStackTrace();
   }
}
}

@SuppressWarnings("deprecation")
public class HibernateSessionFactory {

        /// <summary>
        /// 创制时间
        /// </summary>
        public DateTime? CreateDt { get; set; }
    }
}

CREATE DEFINER=`root`@`localhost` PROCEDURE `insertUser`(nameVar varchar(16),remarkVar varchar(16))

  你还要非常注意的是在创建此测量试验项目在此之前您一定要在品种中引用此项目所援助的顾客 Hibernate包和参预连接 MySQL的连年 jar,若无做此步骤,你的项目是不或许没有问题运行成功的。如未有其它分外的话,作者想应该能够健康实践插入操作了……

    private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
    private static final ThreadLocal<Session> threadLocal = 
            new ThreadLocal<Session>();
    private static Configuration configuration = new Configuration();
    private static SessionFactory sessionFactory;
    private static String configFile = CONFIG_FILE_LOCATION;
    
    static {
        sessionFactory = configuration.configure(configFile).buildSessionFactory();
    }
    
    private HibernateSessionFactory(){
        
    }
    
    public static Session getSession(){
        Session session = threadLocal.get();
        if(session == null || !session.isOpen()){
            session = (sessionFactory != null ) ? sessionFactory.openSession():null;
            threadLocal.set(session);
        }
        return session;
    }
}
复制代码
TestHibernate.java

近日映射这几个User.cs类,新建User.hbm.xml文本同一时候开展布局,如下:

BEGIN

复制代码
 1 package edu.dzu.vo;
 2 
 3 import java.awt.Font;
 4 
 5 import javax.swing.JOptionPane;
 6 
 7 import org.hibernate.Session;
 8 import org.hibernate.Transaction;
 9 
10 public class TestHibernate {
11 
12     /**
13      * @param args
14      */
15     public static void main(String[] args) {
16         
17         Users users = new Users();
18         users.setId(20121108);
19         users.setName("张三");
20         users.setAge(24);
21         users.setTel("010-87654321");
22         users.setAddress("北京黄浦"卡塔尔;
23         
24         Users users2 = new Users();
25         users2.setId(20121109);
26         users2.setName("李四");
27         users2.setAge(23);
28         users2.setTel("010-12345678");
29         users2.setAddress("法国巴黎辽阳"卡塔尔(قطر‎;
30         
31         Session session = HibernateSessionFactory.getSession();
32         Transaction trans = session.beginTransaction();
33         session.persist(users);
34         session.persist(users2);
35         trans.commit();
36         
37         StringBuffer result = new StringBuffer();
38         result.append("增多功成业就!往数据库中增添如下数据:n");
39         result.append("编号"+"地址"+"姓名"+"年龄"+"联系电话trnrn");
40         result.append(users.getId()+" ");
41         result.append(users.getAddress()+" ");
42         result.append(users.getName()+" ");
43         result.append(users.getAge()+" ");
44         result.append(users.getTel()+"tnr");
45         
46         result.append(users2.getId()+" ");
47         result.append(users2.getAddress()+" ");
48         result.append(users2.getName()+" ");
49         result.append(users2.getAge()+" ");
50         result.append(users2.getTel()+"tnr");
51         
52         session.close();
53         
54         JOptionPane.getRootFrame().setFont(new Font("Arial", Font.BOLD, 14));
55         JOptionPane.showMessageDialog(null, result.toString());
56         
57     }
58 
59 }

<?xml version="1.0" encoding="utf-8" ?>
  <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
    namespace="Subject.Model" assembly="Subject.Model">
  <class name="Subject.Model.User" table="User" lazy="false">
    <id name="Id">
      <column name="Id" sql-type="varchar(40)" not-null="true"/>
      <generator class="uuid.hex" />
    </id>
    <property name="Name">
      <column name="Name" sql-type="varchar(20)" not-null="false" />
    </property>
    <property name="Password">
      <column name="Password" sql-type="varchar(20)" not-null="false" />
    </property>
    <property name="Sex">
      <column name="Sex" sql-type="varchar(2)" not-null="false" />
    </property>
    <property name="BriefIntroduction">
      <column name="BriefIntroduction" sql-type="varchar(500)" not-null="false" />
    </property>
    <property name="CreateDt">
      <column name="CreateDt" sql-type="datetime" not-null="false" />
    </property>
  </class>
</hibernate-mapping>

   insert into user(name,remark) values(nameVar,remarkVar);

在乎设置User.hbm.xml文件属性,XML文件的默许生成操作为“内容”,这里须要校勘为“嵌入的财富”,

END;

接下来测验:

三、User.hbm.xml

  public IList<User> Get()
        {
            try
            {
                return _session.CreateQuery("from Subject.Model.User").List<User>();
            }
            catch (Exception e)
            {
                throw;
            }
        }

<hibernate-mapping>

发觉数目为空,如图:

   <class name="com.cj.proc.hibernate.User" table="user" catalog="temp">

图片 2

   <id name="id" type="java.lang.Integer">

不容许啊?因为数据Curry有多少啊,如图:

   <column name="ID" />

图片 3

   <generator class="native"></generator>

那是怎么回事,找了持久,终于被自身找到题指标四方,如图:

   </id>

图片 4

   <property name="name" type="java.lang.String">

本来要加那些,不过运维之后又冒出了难题,唉,写个NHibernate现身这么多难点,自个儿跟本人说:淡定!

   <column name="NAME" length="16" not-null="true" />

图片 5

   </property>

你猜是什么难点?原本Sqlserver二零一零系统表里有User表,你再建那几个表就能够有歧义,当然就能够不由自主问题了,

   <property name="remark" type="java.lang.String">

由此我把User表改成Users表就OK了!

   <column name="REMARK" length="16" not-null="true" />

图片 6

   </property>

到头来成功了,不轻巧呀!

   </class>

 

   <sql-query name="getUserList" callable="true">

 

   <return alias="aa" class="com.cj.proc.hibernate.User">

   <return-property name="id" column="ID"></return-property>

   <return-property name="name" column="NAME"></return-property>

   <return-property name="remark" column="REMARK"></return-property>

   </return>

   {call getUserList()}

   </sql-query>

</hibernate-mapping>

四、调用

1、获取顾客消息

Session session = HibernateSessionFactory.getSession();

Query query = session.getNamedQuery("getUserList");

//query.setString(0, ""卡塔尔;设置参数

List<User> list = query.list();

for(User user:list){

   System.out.println(user.getName()+" "+user.getRemark());

}

2、通过传播参数创设客户

Session session = HibernateSessionFactory.getSession();

Transaction tx = session.beginTransaction();

Connection conn = session.connection();

String proc = "call insertUser(?,?)";

CallableStatement cs = conn.prepareCall(proc);

cs.setString(1, "LINRZ");

cs.setString(2, "REMARK");

cs.execute();

tx.commit();

调用查询存款和储蓄进程时,调用session.getNamedQuery("…"卡塔尔国方法来获取User.hbm.xml中布署的询问存款和储蓄进程。别的存款和储蓄进度的调用,先通过hibernate的session得到connection,然后调用connection对象的相应措施来落实存储进程的调用。

本文由10bet手机官网发布于面向对象,转载请注明出处:hibernate调用存储过程,一个简单使用

上一篇:大型网站后台架构的Web,Web应用缓存系统的分类 下一篇:前端性能优化,关于web端的优化
猜你喜欢
热门排行
精彩图文