您的位置:新葡亰496net > 奥门新萄京娱乐场 > 有关Hibernate中JUnit版本招致空指针非常难点,教程

有关Hibernate中JUnit版本招致空指针非常难点,教程

发布时间:2019-11-09 07:48编辑:奥门新萄京娱乐场浏览(75)

    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索罗德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;

    目录

    率先本身说澳优下自个儿遭逢的标题:初次应用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);
    //提交业务(不可少卡塔 尔(英语:State of Qatar)
    tc.commit();
    }catch(Exception e){
    //数据操作退步,回滚事务
    tc.rollback();
    }
    //关闭session
    session.close();
    }
    }
    代码分层优化:
    获取Session的HibernateGetSession类:
    package com.edu.dbconn;
    新葡亰496net,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

    新葡亰496net 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

    新葡亰496net 2

    4.      总结... 7

    图片.png

    附:关联知识点... 7

    工程:

    知识点1:C#静态构造函数... 7

    新葡亰496net 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#就没非常的学习过,直接就进行拿来用了卡塔 尔(英语:State of Qatar),.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;
    有关Hibernate中JUnit版本招致空指针非常难点,教程入门。}
    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;
    }
    public void setAddress(String address) {
    this.address = address;
    }
    public User() {
    super();
    }
    }

    支出条件:

    User.hbm.xml文件:
    <?xml version="1.0"?>
    有关Hibernate中JUnit版本招致空指针非常难点,教程入门。<!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;

           直接下载 官方网站地址(自个儿下载网速真的好慢卡塔 尔(英语:State of Qatar)

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

           可能利用VS二零一二附带的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>

    新葡亰496net 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_.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

    新葡亰496net 5

     

     

    划入眼:在那之中对于Nhibernate的布局文件(hibernate.cfg.xml与ClassMapping文件,对于转变的操作,必须选择始终复制和嵌入式能源。(不然编写翻译调节和测量试验的时候汇合世bug,比如未有Model Class的Mapping等等卡塔 尔(阿拉伯语:قطر‎。

    1. 测验项目详细解释

    3.1     初始化C#消除方案NHOne(调控台应用程序和相应的测量检验项目卡塔尔

           给每一个品种增进Nhibernate引用,测量试验项目也急需(直接NuGet命令安装就可以卡塔 尔(英语:State of Qatar)

    3.2     编写NHibernate配置文件

           在NHOne的根目录下加多hibernate.cfg.xml文件(生成操作嵌入式财富和始终复制卡塔尔,在文书档案属性中架构选拔hibernate-configuration-2.2 & hibernate-mapping-2.2八个文件,那样编写hibernate.cfg.xml就能够有机动提醒的效果(那七个公文在大家解决方案NHOne的packages/Nhibernate目录中卡塔 尔(英语:State of Qatar)

     新葡亰496net 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() 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卡塔 尔(英语:State of Qatar),铅白部分 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();

           

            }

     

    调节和测量试验程序:

    新葡亰496net 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(编写翻译):编写翻译代码文件,日常的代码文件须要编写翻译

           Embedded Resource(嵌入式资源):将该公文作为DLL或可实行文件嵌入到主目录中,平日用于能源文件,举个例子Nhibernate的布局文件等等。

     

    本文由新葡亰496net发布于奥门新萄京娱乐场,转载请注明出处:有关Hibernate中JUnit版本招致空指针非常难点,教程

    关键词:

上一篇:内置函数,高阶函数

下一篇:没有了