澳门新萄京官方网站-www.8455.com-澳门新萄京赌场网址

澳门新萄京官方网站:教程入门,hibernate开发步

2019-12-12 作者:www.8455.com   |   浏览(109)

Nhibernate 4.0 教程

        遇到的问题描述:Hibernate中JUnit版本导致空指针异常问题

Hibernate框架开拓步骤
体系导入必要的jar包:

编写hibernate.cfg.xml文件
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
澳门新萄京官方网站,          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          ";
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
    <session-factory>
        <!-- 配置连接数据库音讯 -->
        <!-- 加载数据库的U宝马7系L -->
        <property name="connection.url">jdbc:mysql://127.0.0.1:3306/test</property>
        <!-- 数据库连接名 -->
        <property name="connection.username">root</property>
        <!-- 数据库的连年密码 -->
        <property name="connection.password">123456</property>
        <!-- 加载数据库驱动 -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>   
    <!-- 配置hibernate属性音信 -->
    <!-- 设置数据库方言 -->
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    <!-- 后台是不是出示SQL语句 -->
    <property name="show_sql">true</property>
    <!-- 是不是格式化SQL语句 -->
    <property name="format_sql">true</property>
    <!-- 设置数据库生成战略 默认为update-->
    <property name="hbm2ddl.auto">update</property>
    <!-- 加载hibernate映射文件 -->
    <mapping resource="com/edu/bean/User.hbm.xml"/>
    </session-factory>
</hibernate-configuration>
编辑实体类,创设表
eg:
package com.edu.bean;

目录

率先作者表达大器晚成(Wissu卡塔尔(قطر‎下自个儿超越的题目:初次选取Hibernate时,未有留意听项目领导介绍Hibernate,而使用了Hibernate中的JUnit5,甚至于后边向来现身空指针格外,排
除也免去不了,代码找不到不当。
上面是本身的数据库、工程和代码:
数据库:

public class User {
private int id;
private String username;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = 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 User(String username, String password) {
super();
this.username = username;
this.password = password;
}
public User() {
// TODO Auto-generated constructor stub
}
}
编纂映射文件
eg:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
";
<hibernate-mapping>
<!-- name对应实体类,table对应数据库中的表 -->
<class name="com.edu.bean.User" table="user">
<!-- name对应实体类中属性名,column对应表中字段 ,type为表中字段类型-->
<id name="id" column="id">
<!-- 设置主键生成攻略 -->
<generator class="identity"></generator>
</id>
<property name="username" type="string" column="username"></property>
<property name="password" type="string" column="password"></property>
</class>
</hibernate-mapping>
将映射文件放入到hibernate.cfg.xml
<!-- 加载hibernate映射文件 -->
<mapping resource="com/edu/bean/User.hbm.xml"/>
编写代码:
eg:
package com.edu.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;
import com.edu.bean.User;
public class HibernateTest {
@Test
public void test(){
//读取hibernate.cfg.xml主配置文件
Configuration cfg=new Configuration().configure("hibernate.cfg.xml");
//创建SessionFactory工厂
SessionFactory sf=cfg.buildSessionFactory();
//获取session
Session session=sf.openSession();
//创制专业
Transaction tc=session.beginTransaction();
//创建User对象
User user=new User("张三", "123456");
//悠久化对象
try{
//保存数据
session.save(user);
//提交业务(不可少)
tc.commit();
}catch(Exception e){
//数据操作战败,回滚事务
tc.rollback();
}
//关闭session
session.close();
}
}
代码分层优化:
获取Session的HibernateGetSession类:
package com.edu.dbconn;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateGetSession {
//保险SessionFactory工厂只成立一次
private static SessionFactory sf;
static{
if(sf==null){
//读取hibernate.cfg.xml主配置文件
Configuration cfg=new Configuration().configure("hibernate.cfg.xml");
//创建SessionFactory工厂
sf=cfg.buildSessionFactory();
}
}
public static Session getSession(){
//创建session
Session session=sf.openSession();
return session;
}
}
Dao层的UserDao类:
package com.edu.dao;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.edu.bean.User;
import com.edu.dbconn.HibernateGetSession;

1.      下载Nhibernate 4.04. 1

澳门新萄京官方网站 1

public class UserDao {
public void saveUser(){
//获取session
Session session=HibernateGetSession.getSession();
//创立专业
Transaction tc=session.beginTransaction();
//创建User对象
User user=new User("李四", "123456");
//长久化对象
try{
//保存数据
session.save(user);
//提交业务(不可少)
tc.commit();
}catch(Exception e){
//数据操作失利,回滚事务
tc.rollback();
}
//关闭session
session.close();
}
}
测试层:
package com.edu.test;
import org.junit.Test;
import com.edu.dao.UserDao;
public class HibernateTest {
@Test
public void test(){
UserDao ud=new UserDao();
ud.saveUser();
}
}
实例源码:

2.      入门教程... 2

图片.png

3.      测验项目详整... 3

澳门新萄京官方网站 2

4.      总结... 7

图片.png

附:关联知识点... 7

工程:

知识点1:C#静态布局函数... 7

澳门新萄京官方网站 3

知识点2:关于Visual Studio文件生成操作... 8

1.png

 

代码:UserDao.java类
package com.qianfeng.dao;

 

import org.hibernate.Session;
import com.qianfeng.model.User;
import com.qianfeng.tools.DBUtil;

前言:

public class UserDao {
public User selectById(Integer id) {
Session session=DBUtil.findsession();
User user = (User) session.get(User.class,id);
return user;
}
}

       为什么会有其生机勃勃框架?那就牵涉进了Java和C#的恩恩怨怨,Java是开源的面向对象语言的象征,围绕Java的有数不完的开源框架,个中ORM框架(不要问作者怎么是ORM框架)中的最夺目标表示正是Hibernate;C#也是Microsoft紧跟在Java前边推出的面向对象的语言,这七个经常度太大了(作者读书本人攻读的Java,前边C#就没特别的就学过,直接就实行拿来用了),.NET开垦者也参照Hibernate开垦了三个针对.NET平台下的ORM 框架,也正是Nhibernate。

User.java类:
package com.qianfeng.model;

 

import java.io.Serializable;
public class User implements Serializable {
private Integer id;
private String username;
private String password;
private Integer gender;
private Integer age;
private String address;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = 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 Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getAddress() {
return address;
澳门新萄京官方网站:教程入门,hibernate开发步骤。}
public void setAddress(String address) {
this.address = address;
}
public User() {
super();
}
}

支付景况:

User.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">

       Windows 7

<hibernate-mapping>
<class name="com.qianfeng.model.User" table="JAVATEST">

       Visual Studio 2013

<id name="id" column="ID"></id>

       Nhibernate 4.04

<property name="username" column="USERNAME"></property>
<property name="password" column="PASSWORD"></property>
<property name="gender" column="GENDER"></property>
<property name="age" column="AGE"></property>
<property name="address" column="ADDRESS"></property>
</class>
</hibernate-mapping>

       Microsoft Sql Server 2012

HibernateTest.java类:
package com.qianfeng.test;

  1. 下载Nhibernate 4.04

//import org.junit.Before;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import com.qianfeng.dao.UserDao;
import com.qianfeng.model.User;

       直接下载 官方网站地址(自个儿下载网速真的好慢)

public class HibernateTest {
//UserDao dao;
/@Before
public static void init() {
dao=new UserDao();
}
/
static UserDao dao;
@BeforeAll
public static void init() {
dao=new UserDao();
}
@Test
public void test() {
System.out.println(dao);
User user=dao.selectById(1);
System.out.println(user); System.out.println(user.getId() "," user.getUsername() "," user.getPassword());
}
}

      NHibernate is a mature, open source object-relational mapper for the .NET framework. It's actively developed, fully featured and used in thousands of successful projects.

DBUtil.java类:
package com.qianfeng.tools;

       官方网址介绍了Nhibernate是针对.NET框架的老到的、开源的面向关系型数据库映射(ORM).

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class DBUtil {
static SessionFactory sf;
static {
Configuration cfg=new Configuration().configure("hibernate.cfg.xml");
sf = cfg.buildSessionFactory();
}
public static Session findsession() {
return sf.openSession();
}
public static void main(String[] args) {
//初始化Hibernaete.cfg.xml文件
Configuration cfg=new Configuration().configure("hibernate.cfg.xml");
//初始化SessionFactory工厂
SessionFactory sf = cfg.buildSessionFactory();
System.out.println(sf.openSession());
}
}

       或许使用VS2012附带的NuGet管理程序直接设置(NuGet,.NET上面三个开源的前后相继包管理工科具):Install-Package Nhibernate(极其的快卡塔尔国

hibernate.cfg.xml文件:
<?xml version="1.0"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>

澳门新萄京官方网站 4

<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/javaee</property>
<property name="connection.username">root</property>
<property name="connection.password">123</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>

 

<property name="show_sql">true</property>

 

<property name="format_sql">true</property>

  1. 入门教程

<mapping resource="com/qianfeng/model/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>

       新建贰个体系NHOne和测验程序,并且增加对于该品种的测量检验项目,项目结构如下:

里面测验类中自己利用的是JUnit5,因为领导是JUnit4,全部我细心核实了代码,发现代码是从未特别的,这里注意自个儿利用的是被批注的HibernateTest类的@Before,故测量检验结果一向报User user=dao.selectById(1卡塔尔;那句空指针万分,小编很意外,在这一句后边加了出口测量检验System.out.println(dao卡塔尔;开采dao为null;后边通晓到原本是JUnit5中,开始化dao出错了,不应当用@Before,而应当用@BeforeAll,况兼通过看@BeforeAll源码能够了然到该方式必需为静态,这就是JUnit5和JUnit4的区分之意气风发。
怀有作者改掉之后
//UserDao dao;
/@Before
public static void init() {
dao=new UserDao();
}
/
static UserDao dao;
@BeforeAll
public static void init() {
dao=new UserDao();
}
结果就出去了:
Hibernate:
select
user0_.ID as ID0_0_,
user0_.USERNAME as USERNAME0_0_,
user0_澳门新萄京官方网站:教程入门,hibernate开发步骤。.PASSWORD as PASSWORD0_0_,
user0_.GENDER as GENDER0_0_,
user0_.AGE as AGE0_0_,
user0_.ADDRESS as ADDRESS0_0_
from
JAVATEST user0_
where
user0_.ID=?
com.qianfeng.model.User@2638011
1,XXX,123

澳门新萄京官方网站 5

 

 

划入眼:在那之中对于Nhibernate的布置文件(hibernate.cfg.xml与ClassMapping文件,对于转变的操作,必得选用始终复制和嵌入式财富。(不然编写翻译调节和测验的时候会现出bug,比方没有Model Class的Mapping等等)。

  1. 测量检验项目详细明白

3.1     初始化C#应用方案NHOne(调整台应用程序和对应的测验项目)

       给每一个门类拉长Nhibernate引用,测量检验项目也必要(直接NuGet命令安装就可以)

3.2     编写NHibernate配置文件

       在NHOne的根目录下增加hibernate.cfg.xml文件(生成操作嵌入式能源和一向复制),在文书档案属性中布局接受hibernate-configuration-2.2 & hibernate-mapping-2.2多少个文本,这样编写hibernate.cfg.xml就能有活动提醒的机能(那四个文件在我们解决方案NHOne的packages/Nhibernate目录中)

 澳门新萄京官方网站 6

 

hibernate.cfg.xml 具体内容如下:

<?xml version="1.0" encoding="utf-8" ?>

<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">

  <session-factory>

    <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>

    <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>

    <property name="connection.connection_string">Data Source=localhost;user=sa;password=12345;Initial Catalog=test</property>

    <property name="dialect">NHibernate.Dialect.MsSql2012Dialect</property>

    <property name="show_sql">true</property>

    <property name="hbm2ddl.auto">update</property>

   

    <!--Mapping files 嵌入式财富 表格table 名字不得以是user-->

    <mapping  assembly="NHOne"/>

  </session-factory>

 

</hibernate-configuration>

 

<mapping assembly=”NHOne”/> 这里写的是类其余名字,然后就能招来项目上边全部的后缀是.hbm.xml的文书,也足以手动本人丰盛,相比费心,有机会再详尽疏解。

3.3     编写Model Class “User”

         全体的属性皆以使用virtual来修饰(延迟加载有用),增多对应的get set方法

         在MSServer 中,user 是非同一般字,因而不可以有user的报表,能够应用此外来代替

         在事实上行使中,种种model类,很只怕供给提供Equals(卡塔尔(英语:State of Qatar) HashCode(卡塔尔ToString(卡塔尔(قطر‎方法的重写

namespace NHOne.Model

{

    public class User

    {

        private string id;

        private string username;

        private string password;

        private char gender; //"F" & "M"

        private int age;

        private string phone;

 

        public User()

        {

 

        }

 

        public User(string username, string password, char gender, int age, string phone)

        {

            this.username = username;

            this.password = password;

            this.gender = gender;

            this.age = age;

            this.phone = phone;

        }

 

        public User(string id, string username, string password, char gender, int age, string phone)

        {

            this.id = id;

            this.username = username;

            this.password = password;

            this.gender = gender;

            this.age = age;

            this.phone = phone;

        }

        public virtual string Id { get; set; }

        public virtual string Username { get; set; }

        public virtual string Password { get; set; }

        public virtual char Gender { get; set; }

        public virtual int Age { get; set; }

        public virtual string Phone { get; set; }

        public override bool Equals(object obj)

        {

            if (this == obj)

            {

                return true;

            }

            User user = obj as User;

            if (user == null)

            {

                return false;

            }

            else

            {

                return this.Username.Equals(user.Username);

            }

        }

 

        public override int GetHashCode()

        {

            return Username.GetHashCode();

        }

 

        public override string ToString()

        {

            return "id:" Id ";  Username:" Username ";  Password:" Password ";  Gender:" Gender ";  Age:" Age ";    Phone:" Phone;

        }

    }

}

3.4  编写Model的Mapping文件

    坐落于Mapping目录上边新建文件User.hbm.xml文件(嵌入式财富,添Gavin书的构造为hibernate-mapping-2.2.xml),黑古铜色部分 assembly是系列的名号,namespace是在等级次序中Model类的命名空间,若是简单的话,须要在末端的class name属性中填入完整的名字空间和类名。

瞩目table的名字不能够写成user,不然报错,因为user是数据库的机要字

内容如下:

<?xml version="1.0" encoding="utf-8" ?>

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="NHOne" namespace="NHOne.Model" default-lazy="true">

  <class name="User" table="client">

    <id name="Id">

      <column name="user_id" sql-type="char(32)" not-null="true"/>

      <generator class="uuid.hex"/>

    </id>

    <property name="Username" column="username"  not-null="true"/>

    <property name="Password" column="password" not-null="true" />

    <property name="Gender"   column="gender"   />

    <property name="Age"      column="age"      />

    <property name="Phone"    column="phone"    />

  </class>

</hibernate-mapping>

 

3.5    编写NHibernate的拔刀相助类,最初化NHibernate的条件,获取Session

       在Util命名空间下,增添YangNHibernate的类,具体内容如下:

namespace NHOne.Util

{

    public class YangNHibernate

    {

        private static readonly  ISessionFactory sessionFactory;

        private static string HibernateHbmXmlFileName = "hibernate.cfg.xml";

        //private static ISession session

        static YangNHibernate()

        {

            sessionFactory = new Configuration().Configure().BuildSessionFactory();

        }

        public static ISessionFactory getSessionFactory()

        {

            return sessionFactory;

        }

        public static ISession getSession()

        {

            return sessionFactory.OpenSession();

        }

        public static void closeSessionFactory()

        {

            

        }

    }

}

 

3.6    编写测量检验代码

       在测量试验类中测验保存User到数据库,使用专门的学业的体制

        [TestMethod]

        public void TestSaveUser()

        {

            User user = createUser();

            ISession session  = YangNHibernate.getSession();

            ITransaction tx = session.BeginTransaction();

            session.Save(user);

            tx.Commit();

            session.Close();

       

        }

 

调节和测量检验程序:

澳门新萄京官方网站 7

 

 

 

  1. 总结

       NHibernate是C#程序猿,参照Java的ORM框架Hibernate实现的一个开源项目,在C#中项目支出中相当的方便人民群众高效,让技师从繁缛的SQL语句中解放出来,对于项指标模块化相当好用。

       测验项目标源代码地址:

                

参照文书档案:

  1. NHibernate官网
  2. MSDN for C#:

附:关联知识点

知识点1:C#静态结构函数

C#至于静态布局函数的知识,自动调用最初化静态的成员属性,尤其是readonly修饰的静态属性,与Java中的静态代码块近似。

参照MSDN给出的表明:

       A static constructor is used to initialize any static.aspx) data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced.

()

       因为静态布局函数是.NET自动调用的,因而改代码块就没有必要利用修饰符修饰。

关于C#静态结构函数的性状,具体如下:

       A static constructor does not take access modifiers or have parameters.

       A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.

       A static constructor cannot be called directly.

       The user has no control on when the static constructor is executed in the program.

       A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.

       Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.

       If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running.

 

知识点2:关于Visual Studio文件生成操作

Visual Studio生成操作有以下多少个选项:

       Non(无):也正是在项目转移的时候不开展别的的操作,在转移的目录中并未此文件,平日用来项目描述文件.

       Content(内容卡塔尔(قطر‎:也正是将文件直接复制到输出目录中,常常用于html等静态文件.

       Compile(编译卡塔尔(英语:State of Qatar):编写翻译代码文件,平时的代码文件必要编译

       Embedded Resource(嵌入式财富卡塔尔国:将该公文作为DLL或可试行文件嵌入到主目录中,经常用于能源文件,举例Nhibernate的布置文件等等。

 

本文由澳门新萄京官方网站发布于www.8455.com,转载请注明出处:澳门新萄京官方网站:教程入门,hibernate开发步

关键词: