本文共 11418 字,大约阅读时间需要 38 分钟。
package cn.edu.hpu.user.model;public class User { private int id; private String username; private String password; private String nickname; 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 String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } }我们要存储对象至数据库,就需要使用hibernate,那么我们就需要在POM配置文件中去引入它,因为我们不知道该怎么去写相应的配置参数,所以我们要登录mvnrepository.com,利用中央仓库的搜索引擎去找到我们需要的jar包,点击相应jar包可以找到配置参数: 我们把提供的配置拷贝至我们的pom文件中:
然后我们的项目的环境中就有了这个jar包 其实是maven从网络中心仓库下载至我们本地仓库中的: hibernate引入后,然后修改我们的user,给它加上注解:org.hibernate hibernate-entitymanager 4.1.10.Final
package cn.edu.hpu.user.model;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.Table;@Entity@Table(name="t_user")public class User { private int id; private String username; private String password; private String nickname; public User() { super(); } public User(String username, String password, String nickname) { super(); this.username = username; this.password = password; this.nickname = nickname; } public User(int id, String username, String password, String nickname){ super(); this.id = id; this.username = username; this.password = password; this.nickname = nickname; } @Id @GeneratedValue 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 String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } }然后我们在pom中加上mysql的数据库连接驱动:
然后是log4j的:mysql mysql-connector-java 5.1.24
然后接下来写hibernate的配置文件:log4j log4j 1.2.17
以及log4j配置文件:root 1234 com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/maven_user true org.hibernate.dialect.MySQL5Dialect update true true
log4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.Target=System.outlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p [%t] %c{1}:%L - %m%nlog4j.rootLogger=warn, stdout, Rlog4j.logger.cn.edu.hpu=debuglog4j.appender.R=org.apache.log4j.DailyRollingFileAppenderlog4j.appender.R.File=F:/tax/UserSys.loglog4j.appender.R.layout=org.apache.log4j.PatternLayoutlog4j.appender.R.layout.ConversionPattern=%d [%t] %5p %c - %m%n现在我们完成了所有配置,接下来写HibernateUtil来获取SessionFactory:
package cn.edu.hpu.user.util;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.boot.registry.StandardServiceRegistryBuilder;import org.hibernate.cfg.Configuration;import org.hibernate.service.ServiceRegistry;public class HibernateUtil { private final static SessionFactory FACTORY = buildSessionFactory(); private static SessionFactory buildSessionFactory() { Configuration cfg=new Configuration().configure(); ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry(); SessionFactory factory=cfg.buildSessionFactory(serviceRegistry); return factory; } public static SessionFactory getFactory() { return FACTORY; } public static Session openSession(){ return FACTORY.openSession(); } public static void close(Session session){ if(session!=null) session.close(); } }接下来我们来编写Dao层: IUserDao:
package cn.edu.hpu.user.dao;import cn.edu.hpu.user.model.User;public interface IUserDao { public void add(User user); public User loadUsername(String username);}UserDao:
package cn.edu.hpu.user.dao;import org.hibernate.Session;import cn.edu.hpu.user.model.User;import cn.edu.hpu.user.util.HibernateUtil;public class UserDao implements IUserDao { public void add(User user) { Session session = null; try { session=HibernateUtil.openSession(); session.beginTransaction(); session.save(user); session.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); }finally{ HibernateUtil.close(session); } } public User loadUsername(String username) { Session session = null; User user=null; try { session=HibernateUtil.openSession(); user=(User) session.createQuery("from User where username=?") .setParameter(0, username).uniqueResult(); } catch (Exception e) { e.printStackTrace(); }finally{ HibernateUtil.close(session); } return user; }}由于我们接下来要隔离数据库进行操作,所以需要dbunit工具类,我们在pom中导入它:
测试不要和hibernate的Connection混用,我们使用原始的JDBC的链接: DbUtil:dbunit dbunit 2.2
package cn.edu.hpu.user.util;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;public class DbUtil { // 定义MySQL的数据库驱动程序 public static final String DBDRIVER = "org.gjt.mm.mysql.Driver" ; //定义mysql的数据库连接地址: public static final String DBDURL = "jdbc:mysql://localhost:3306/maven_user" ; //mysql数据库的连接用户名 public static final String DBUSER = "root" ; //mysql数据库的连接密码 public static final String DBPASS = "1234" ; static{ try { Class.forName(DBDRIVER); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static Connection getConnection(){ Connection conn=null; try { conn=DriverManager.getConnection(DBDURL,DBUSER,DBPASS); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return conn; } public static void close(ResultSet rs,Statement st,Connection conn){ try { if(rs!=null){ rs.close(); } if(st!=null){ st.close(); } if(conn!=null){ conn.close(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void close(Statement st,Connection conn){ close(null,st,conn); }}接下来编写AbstractDbUnitTestCase和EntitiesHelper两个测试用类 AbstractDbUnitTestCase:
package cn.edu.hpu.user.util;import java.io.File;import java.io.FileWriter;import java.io.IOException;import java.io.InputStream;import java.sql.SQLException;import org.dbunit.DatabaseUnitException;import org.dbunit.database.DatabaseConnection;import org.dbunit.database.IDatabaseConnection;import org.dbunit.database.QueryDataSet;import org.dbunit.dataset.DataSetException;import org.dbunit.dataset.IDataSet;import org.dbunit.dataset.xml.FlatXmlDataSet;import org.dbunit.operation.DatabaseOperation;import org.junit.AfterClass;import org.junit.Assert;import org.junit.BeforeClass;public class AbstractDbUnitTestCase { public static IDatabaseConnection dbunitCon; private File tempFile; @BeforeClass public static void init() throws Exception{ dbunitCon = new DatabaseConnection(DbUtil.getConnection()); } protected IDataSet createDataSet(String tname)throws DataSetException,IOException{ InputStream is=AbstractDbUnitTestCase .class .getClassLoader().getResourceAsStream("dbunit_xml/"+tname+"xml"); Assert.assertNotNull("dbunit的基本数据文件不存在!", is); return new FlatXmlDataSet(is); } protected void backupAllTable() throws SQLException,IOException,DataSetException{ IDataSet ds=dbunitCon.createDataSet(); writeBackupFile(ds); } private void writeBackupFile(IDataSet ds) throws IOException, DataSetException { tempFile=File.createTempFile("back","xml"); FlatXmlDataSet.write(ds, new FileWriter(tempFile)); } protected void backupCustomTable(String [] tname)throws DataSetException, SQLException, IOException{ QueryDataSet ds=new QueryDataSet(dbunitCon); for(String str:tname){ ds.addTable(str); } writeBackupFile(ds); } protected void backupOneTable(String tname)throws DataSetException, SQLException, IOException{ backupCustomTable(new String[]{tname}); } protected void resumeTable() throws IOException, DatabaseUnitException, SQLException{ IDataSet ds=new FlatXmlDataSet(tempFile); DatabaseOperation.CLEAN_INSERT.execute(dbunitCon,ds); } @AfterClass public static void destory(){ try { if(dbunitCon!=null) dbunitCon.close(); } catch (SQLException e) { e.printStackTrace(); } }}EntitiesHelper:
package cn.edu.hpu.user.util;import org.junit.Assert;import cn.edu.hpu.user.model.User;public class EntitiesHelper { private static User baseUser=new User(1,"admin","123","管理员"); public static void assertUser(User expected,User actual){ Assert.assertNotNull(expected); Assert.assertEquals(expected.getId(), actual.getId()); Assert.assertEquals(expected.getUsername(), actual.getUsername()); Assert.assertEquals(expected.getPassword(), actual.getPassword()); Assert.assertEquals(expected.getNickname(), actual.getNickname()); } public static void assertUser(User expected){ assertUser(expected,baseUser); }}然后我们写一下user的文件t_user.xml,将其放入src/test/resource中
然后开始写测试类:
package cn.edu.hpu.user.dao;import java.io.IOException;import java.sql.SQLException;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.Assert;import org.junit.Before;import org.junit.Test;import cn.edu.hpu.user.model.User;import cn.edu.hpu.user.util.AbstractDbUnitTestCase;import cn.edu.hpu.user.util.EntitiesHelper;public class TestUserDao extends AbstractDbUnitTestCase{ private IUserDao userDao; @Before public void setUp() throws DataSetException, SQLException, IOException{ userDao =new UserDao(); backupOneTable("t_user"); } @Test public void testLoad() throws IOException, DatabaseUnitException, SQLException{ IDataSet ds=createDataSet("t_user"); DatabaseOperation.TRUNCATE_TABLE.execute(dbunitCon, ds); User tu=userDao.loadUsername("admin"); EntitiesHelper.assertUser(tu); } @Test public void testAdd() throws IOException, DatabaseUnitException, SQLException{ IDataSet ds=createDataSet("t_user"); DatabaseOperation.TRUNCATE_TABLE.execute(dbunitCon, ds); User user=new User("admin","123","管理员"); userDao.add(user); Assert.assertTrue(user.getId()>0); User tu=userDao.loadUsername("admin"); EntitiesHelper.assertUser(tu,user); } @After public void tearDown() throws IOException, DatabaseUnitException, SQLException{ resumeTable(); } }然后我们鼠标右键点击项目,然后选择Run As...,然后选择Maven Build: 我们输入两个指令(clean test),现清空,然后再测试: 结果在控制台中显示,target文件夹中的测试报告中也有(如果出错了,点击txt有结果,点击下面Junit的txt文件会跳转至Junit测试台):
我们算是完成了项目中一部分模块了,下一次我们将写下一个模块,日志模块。
转载请注明出处: