一步一步做项目(9)实体类测试
在前面一步一步做项目(5)管理用户信息java类的实现中介绍了实体类的创建,那么,怎么进行测试呢?
实体类
首先,来看看,实体类:
package cn.lut.curiezhang.model;
/**
* SSH框架进行用户管理的持久层的POJO类
* @author curiezhang
*
*/
public class Users {
// 用户id
private String userId;
// 用户名
private String userName;
// 用户密码
private String userPassword;
// 用户联系电话
private String userPhone;
public Users() {
super();
}
public Users(String userId, String userName, String userPassword) {
super();
this.userId = userId;
this.userName = userName;
this.userPassword = userPassword;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public String getUserPhone() {
return userPhone;
}
public void setUserPhone(String userPhone) {
this.userPhone = userPhone;
}
}
这里,需要创建构造器方法,Users()和Users(String userId, String userName, String userPassword),为创建对象服务的。
Hibernate映射配置
需要设置映射配置文件Users.hbm.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="cn.lut.curiezhang.model.Users" table="USERS">
<id name="userId">
<column name="USER_ID" length="32">
<comment>用户id</comment>
</column>
<generator class="assigned"/>
</id>
<property name="userName">
<column name="USER_NAME" not-null="true" length="50">
<comment>用户名</comment>
</column>
</property>
<property name="userPassword">
<column name="USER_PASSWORD" not-null="true" length="128">
<comment>用户密码</comment>
</column>
</property>
<property name="userPhone">
<column name="USER_PHONE" length="20">
<comment>用户手机</comment>
</column>
</property>
</class>
</hibernate-mapping>
你也可以采用注解的方式来配置,这就需要在实体类中配置注解来进行映射。
Hibernate配置
需要进行Hibernate配置,配置hibernate.cfg.xml文件:
<?xml version='1.0' encoding='utf-8'?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<!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.cj.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/cmis?serverTimezone=GMT%2B8&useSSL=false</property>
<property name="connection.username">cmis</property>
<property name="connection.password">13993106255</property>
<!-- 自动连接支持 -->
<property name="connection.autoReconnect">true</property>
<property name="connection.autoReconnectForPools">true</property>
<property name="connection.is-connection-validation-required">true</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">5</property>
<!-- 每次从数据库中取出并放到JDBC的Statement中的记录条数。Fetch Size设的越大,读数据库的次数越少,速度越快,Fetch Size越小,读数据库的次数越多,速度越慢-->
<property name="jdbc.fetch_size">50 </property>
<!--批量插入,删除和更新时每次操作的记录数。Batch Size越大,批量操作的向数据库发送Sql的次数越少,速度就越快,同样耗用内存就越大-->
<property name="jdbc.batch_size">23 </property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQL8Dialect</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
<mapping resource="cn/lut/curiezhang/model/Users.hbm.xml"/>
</session-factory>
</hibernate-configuration>
这里,需要注意将<mapping resource="cn/lut/curiezhang/model/Users.hbm.xml"/>
添加到配置文件中,这就可以找到Hibernate映射配置文件,当然,你也可以采用注解的方式来配置。
实体测试
现在,已经完成了Hibernate运行环境的基本设置和准备工作,就可以进行测试了,使用Junit测试模块,在eclipse的Java Build Path中,添加库支持,如下图所示,选择对应的Junit库即可。
之后,创建测试类:
package cn.lut.curiezhang.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import cn.lut.curiezhang.model.Users;
import cn.lut.curiezhang.util.SecurityFunctions;
import junit.framework.TestCase;
/**
* Illustrates use of Hibernate native APIs.
*
* @author Curie Zhang
*/
public class UserTest extends TestCase {
private SessionFactory sessionFactory;
@Override
protected void setUp() throws Exception {
// A SessionFactory is set up once for an application!
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
.configure() // configures settings from hibernate.cfg.xml
.build();
try {
sessionFactory = new MetadataSources( registry ).buildMetadata().buildSessionFactory();
}
catch (Exception e) {
// The registry would be destroyed by the SessionFactory, but we had trouble building the SessionFactory
// so destroy it manually.
StandardServiceRegistryBuilder.destroy( registry );
}
}
@Override
protected void tearDown() throws Exception {
if ( sessionFactory != null ) {
sessionFactory.close();
}
}
@SuppressWarnings("unchecked")
public void testBasicUsage() {
// create a couple of user...
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save( new Users( "77777", "77777", SecurityFunctions.sha3("111111", 512) ) );
session.save( new Users( "88888", "88888", SecurityFunctions.sha3("111111", 512) ) );
session.getTransaction().commit();
session.close();
// now lets pull users from the database and list them
session = sessionFactory.openSession();
session.beginTransaction();
List<Users> result = session.createQuery( "from Users" ).list();
for ( Users user : result ) {
System.out.println( "User (" + user.getUserId() + ", " + user.getUserName() + ") : " + user.getUserPassword() );
}
session.getTransaction().commit();
session.close();
}
}
执行
运行测试前,要启动MySQL数据库,然后,执行JUnit Test,如下图所示:
之后,就可以在控制台上看到执行的结果,也可以在数据库中看到执行的结果。
控制台输出如下:
在数据库中的输出如下:
这里使用的数据库客户端是DataGrip。
其它的实体类,也可以通过这样的方法来进行测试,向数据库中添加数据,从数据库删除数据等。