上一章我们已经集成struts2,本章我们主要将mybatis集成进来,方便我们持久层代码的编写。
首先添加相应的包:mybatis-3.1.1.jar,oracle驱动包:ojdbc14.jar
创建管理员用户存储表,用来查询登录页选择管理员的用户,数据稍后再插入。
CREATE TABLE admin( Admin_ID number(11), Admin_Username varchar(20), Admin_Password varchar(20), Admin_Name varchar(20), Admin_Sex varchar(10), Admin_Tel varchar(20) )
创建configuration.xml。
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <!-- 注意:每个标签必须按顺序写,会提示错误:--> <configuration> <!-- 属性配置 --> <properties resource="jdbc.properties"/> <!-- 设置缓存和延迟加载等等重要的运行时的行为方式 --> <settings> <!-- 设置超时时间,它决定驱动等待一个数据库响应的时间 --> <setting name="defaultStatementTimeout" value="25000"/> </settings> <!-- 别名 --> <typeAliases> <typeAlias alias="Admin" type="com.bean.AdminBean"/> </typeAliases> <environments default="development"> <!-- environment 元素体中包含对事务管理和连接池的环境配置 --> <environment id="development"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="${driver}" /> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> </dataSource> </environment> </environments> </configuration>
创建jdbc.properties
driver=oracle.jdbc.driver.OracleDriver url=jdbc:oracle:thin:@127.0.0.1:1521:orcl username=project password=project
创建表对应的实体类:
package com.bean; public class AdminBean { private int Admin_ID ; private String Admin_Username ; private String Admin_Password ; private String Admin_Name ; private String Admin_Sex ; private String Admin_Tel ; public int getAdmin_ID() { return Admin_ID; } public void setAdmin_ID(int adminID) { Admin_ID = adminID; } public String getAdmin_Username() { return Admin_Username; } public void setAdmin_Username(String adminUsername) { Admin_Username = adminUsername; } public String getAdmin_Password() { return Admin_Password; } public void setAdmin_Password(String adminPassword) { Admin_Password = adminPassword; } public String getAdmin_Name() { return Admin_Name; } public void setAdmin_Name(String adminName) { Admin_Name = adminName; } public String getAdmin_Sex() { return Admin_Sex; } public void setAdmin_Sex(String adminSex) { Admin_Sex = adminSex; } public String getAdmin_Tel() { return Admin_Tel; } public void setAdmin_Tel(String adminTel) { Admin_Tel = adminTel; } }
定义admin表的sql映射文件AdminUserMapper.xml,如果遇到mybatis配置问题,请自己查资料了解。
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN" "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd"> <!-- namespace用于java代码调用时识别指定xml的mapper文件 --> <mapper namespace="com.mybatis.model.Admin"> <!-- 配置ORM映射 --> <resultMap type="Admin" id="admin_orm"> <result property="Admin_ID" column="ADMIN_ID"/> <result property="Admin_Username" column="ADMIN_USERNAME"/> <result property="Admin_Password" column="ADMIN_PASSWORD"/> <result property="Admin_Name" column="ADMIN_NAME"/> <result property="Admin_Sex" column="ADMIN_SEX"/> <result property="Admin_Tel" column="ADMIN_TEL"/> </resultMap> <select id="selectByUsernameAndPassword" parameterType="map" resultType="Admin"> SELECT * FROM ADMIN WHERE ADMIN_USERNAME= #{Admin_Username} and ADMIN_PASSWORD=#{Admin_Password} </select> </mapper>
并将AdminUserMapper.xml,注册入configuration.xml中
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <!-- 注意:每个标签必须按顺序写,会提示错误:--> <configuration> <!-- 属性配置 --> <properties resource="jdbc.properties"/> <!-- 设置缓存和延迟加载等等重要的运行时的行为方式 --> <settings> <!-- 设置超时时间,它决定驱动等待一个数据库响应的时间 --> <setting name="defaultStatementTimeout" value="25000"/> </settings> <!-- 别名 --> <typeAliases> <typeAlias alias="Admin" type="com.bean.AdminBean"/> </typeAliases> <environments default="development"> <!-- environment 元素体中包含对事务管理和连接池的环境配置 --> <environment id="development"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="${driver}" /> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> </dataSource> </environment> </environments> <!-- ORM映射文件 --> <mappers> <mapper resource="com/mybatis/model/AdminUserMapper.xml" /> </mappers> </configuration>
创建mybatis的工具类,主要是用于避免重复造轮子,类似JDBC连接、关闭连接一样,用工具类来实现。
package com.utils; import java.io.IOException; import java.io.Reader; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class SessionFactoryUtil { private static final String RESOURCE = "Configuration.xml"; private static SqlSessionFactory sqlSessionFactory = null; private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>(); static { Reader reader = null; try { reader = Resources.getResourceAsReader(RESOURCE); } catch (IOException e) { throw new RuntimeException("Get resource error:"+RESOURCE, e); } sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); } /** * Function : 获得SqlSessionFactory */ public static SqlSessionFactory getSqlSessionFactory(){ return sqlSessionFactory; } /** * Function : 重新创建SqlSessionFactory */ public static void rebuildSqlSessionFactory(){ Reader reader = null; try { reader = Resources.getResourceAsReader(RESOURCE); } catch (IOException e) { throw new RuntimeException("Get resource error:"+RESOURCE, e); } sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); } /** * Function : 获取sqlSession */ public static SqlSession getSession(){ SqlSession session = threadLocal.get(); if(session!=null){ if(sqlSessionFactory == null){ getSqlSessionFactory(); } //如果sqlSessionFactory不为空则获取sqlSession,否则返回null session = (sqlSessionFactory!=null) ? sqlSessionFactory.openSession(): null; } return session; } /** * Function : 关闭sqlSession */ public static void closeSession(){ SqlSession session = threadLocal.get(); threadLocal.set(null); if(session!=null){ session.close(); } } }
创建AdminDao持久层接口以及实现类。
package com.dao; import com.bean.AdminBean; public interface AdminDao { /** * @date 2016-10-18 下午6:03:50 * @Title: CheckLogin * @Description: 根据用户名称以及密码验证是否存在该管理员账号 * @return String 返回类型 * @throws */ public boolean CheckLogin(AdminBean admin); }
package com.dao.impl; import java.util.HashMap; import java.util.Map; import org.apache.ibatis.session.SqlSession; import com.bean.AdminBean; import com.dao.AdminDao; import com.utils.SessionFactoryUtil; public class AdminDaoImpl implements AdminDao{ @Override public boolean CheckLogin(AdminBean admin) { SqlSession session = SessionFactoryUtil.getSqlSessionFactory().openSession(); Map<String,Object> params = new HashMap<String ,Object>(); params.put("Admin_Username", admin.getAdmin_Name()); params.put("Admin_Password", admin.getAdmin_Password()); AdminBean adminbean = (AdminBean) session.selectOne("com.mybatis.model.Admin.selectByUsernameAndPassword", params); session.close(); if(adminbean!=null){ return true; } return false; } }
单元测试类通过显示"用户不存在"
package com.Junit; import org.junit.Test; import com.bean.AdminBean; import com.dao.AdminDao; import com.dao.impl.AdminDaoImpl; public class AdminJunitTest { private AdminDao adminDao=new AdminDaoImpl(); @Test public void testLoad(){ AdminBean bean=new AdminBean(); bean.setAdmin_Name("zhangsan"); bean.setAdmin_Password("123"); boolean exist = adminDao.CheckLogin(bean); if(exist){ System.out.println("用户存在"); } else{ System.out.println("用户不存在!!"); } } }
我们往数据库塞一条数据:
insert into ADMIN (ADMIN_ID, ADMIN_USERNAME, ADMIN_PASSWORD, ADMIN_NAME, ADMIN_SEX, ADMIN_TEL) values (1, ‘zhangsan‘, ‘123‘, ‘张三‘, ‘男‘, ‘159********‘);
执行上面的单元测试,测试结果:“用户存在”。
至此,mybatis的简单集成以及工具类都已经做好,剩下的就是action的配置以及其他功能dao的完成。
本文出自 “进击的程序猿” 博客,请务必保留此出处http://zangyanan.blog.51cto.com/11610700/1863147
原文:http://zangyanan.blog.51cto.com/11610700/1863147