cms04---basic-hibernate03--BaseDao测试

来源:互联网 发布:安卓版ps软件中文版 编辑:程序博客网 时间:2024/06/09 21:28

为了测试类不会打包, 将测试类放到src/test/java.

1.1、测试实体
   使用Entiry注解使实体类为Hibernate所管理。

这里写图片描述

2、测试

问题1:MySQL在高版本需要指明是否进行SSL连接问题

Sun Oct 29 20:40:43 GMT+08:00 2017 WARN: Establishing SSL connection without server's identity verification is not recommended.According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.

解决方案:在url后加上 &useSSL=true

    public static Connection getConnection() throws SQLException {        Connection con = null;        //加上userSSL=true, 解决高版本是否连接SSL        con = DriverManager.getConnection("jdbc:mysql://localhost:3307/cms_test?serverTimezone=UTC&useSSL=true",                 "root", "root");        return con;    }

问题2:beans.xml的配置jdbc时,url后添加参数

Caused by: org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 23 in XML document from class path resource [beans.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 23; columnNumber: 93; 对实体 "useSSL" 的引用必须以 ';' 分隔符结尾。

解决方案:将参数删除。

<property name="url" value="jdbc:mysql://localhost:3307/cms_test?serverTimezone=UTC&useSSL=true;" />改为<property name="url" value="jdbc:mysql://localhost:3307/cms_test />

问题3:pom.xml文件总是显示Project read error

解决方案: Maven–>update project

这里写图片描述

问题4:

org.hibernate.UnknownEntityTypeException: Unable to locate persister: com.chb.basic.model.User

由于在配置beans.xml中,将包名写错了, 大意。

测试代码

package com.chb.basic.dao;import java.io.FileNotFoundException;import java.io.IOException;import java.sql.SQLException;import javax.inject.Inject;import org.chb.basic.test.util.AbstractDbUnitTestCase;import org.chb.basic.test.util.EntitiesHelper;import org.dbunit.DatabaseUnitException;import org.dbunit.dataset.DataSetException;import org.dbunit.dataset.IDataSet;import org.dbunit.operation.DatabaseOperation;import org.junit.After;import org.junit.Before;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.test.context.ContextConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import com.chb.basic.model.User;@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration("classpath:beans.xml") public class TestUserDao extends AbstractDbUnitTestCase{    @Inject//注入    private IUserDao userDao;    @Before    public void  setUp() throws DataSetException, SQLException, IOException {        this.backupAllTable();    }    @Test    public void testLoad() throws DatabaseUnitException, SQLException {        IDataSet dataSet = createDateSet("t_user");        //加载数据集        DatabaseOperation.CLEAN_INSERT.execute(dbunitCon, dataSet);        //测试加载        User u = userDao.load(1);        //拿获取的user与EntriesHelper设置的User对比        EntitiesHelper.assertUser(u);    }    @After    public void tearDown() throws FileNotFoundException, DatabaseUnitException, SQLException {        this.resumeTable();    }}

3、Spring整合dbunit简化测试

3.1、加入依赖

        <!-- Spring整合dbunit  start -->        <dependency>            <groupId>com.github.springtestdbunit</groupId>            <artifactId>spring-test-dbunit</artifactId>            <version>1.3.0</version>            <scope>test</scope>        </dependency>        <!-- Spring整合dbunit  end -->

问题:、被Spring所管理不可以使用openSession(), 而是使用getCurrentSession().

    BaseDao中的getSession()    /**     * 获取Session     * @return     */    protected Session getSession() {        return this.sessionFactory.getCurrentSession();        //return this.sessionFactory.openSession();    }

spring junit解决延迟加载

5、测试删除delete

对象不存在

这里写图片描述

6、测试list

6.1、测试list(String hql, Object[] args)

这里写图片描述

6.2、设置排序方式,
测试com.chb.basic.dao.IBaseDao.list(String hql, Object[] args, map<String Object> alias)

这里写图片描述

6.3、测试IBaseDao.find(String hql, Object[] args), 返回Pager对象。

问题:

org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: order near line 1, column 85 [select count(*) from com.chb.basic.model.User where id>? and id <? order by id desc order by id desc]

原因: 由于在设置select count(*) 的位置错了,导致语句中有两个order by id desc;

这里写图片描述

6.4、基于SQL查询列表对象

    @Test    public void listSqlByArgs() {        String sql = "select * from t_user where id>? and id<?";        Object[] args = new Object[] {1, 7};        List<User> list = userDao.listBySql(sql, args, User.class, true);        for (User user : list) {            System.out.println(user);        }    }

问题:

org.hibernate.QueryException: Expected positional parameter count: 2, actual parameters: [] [select * from t_user where id>? and id<?]

原因: BaseDao中的实现类,将args设置为null,导致的。

测试基于SQL的别名的查询。

    @Test    public void listSqlByAlias() {        SystemContext.setOrder("desc");        SystemContext.setSort("id");        String hql = "select * from t_user where id>? and id <? and id in (:ids)";        Object[] args = new Object[]{2, 6};        //设置别名        Map<String, Object> alias = new HashMap<String, Object>();        alias.put("ids", Arrays.asList(2, 3, 4));        //测试com.chb.basic.dao.IBaseDao.list(String hql, Object[] args, map<String Object> alias)        List<User> list = userDao.listBySql(hql, args, alias, User.class, true);        for (User user : list) {            System.out.println(user);        }    }

6.5、基于别名及参数的SQL的查询

    @Test    public void testFindPagerSQLByArgs() throws DatabaseUnitException, SQLException {        SystemContext.setOrder("desc");        SystemContext.setSort("id");        SystemContext.setPageOffset(0);        SystemContext.setPageSize(3);        String sql = "select * from t_user where id>? and id <? and id in(:ids)";        Object[] args = new Object[]{1, 10};        Map<String, Object> alias = new HashMap<String, Object>();        alias.put("ids", Arrays.asList(5,6,9));        //测试public Pager<T> findBySql(String sql, Object[] args, Map<String, Object> alias, Class<T> clz, boolean hasEntity)        Pager<User> pager = userDao.findBySql(sql, args, alias, User.class, true);        System.out.println(pager.getOffset() + "--- " + pager.getTotal() +"----"+ pager.getSize());        for (User user : pager.getDatas()) {            System.out.println(user);        }    }

问题:

java.lang.ClassCastException: java.math.BigInteger cannot be cast to java.lang.Long

解决,修改BaseDao中的实现

long total = ((BigInteger) cQuery.uniqueResult()).longValue();