标签:
UserDao.java
public interface UserDao{ public User findUserByID(Serializable id); public List<User> findUsersByName(String name); }
UserDaoImpl.java
public class UserDaoImpl implements UserDao{ //SqlSessionFactory是单例存在,不应该在具体实例中创建,需要外部依赖注入 private SqlSessionFactory sqlSessionFactory; public UserDaoImpl(SqlSessionFactory sqlSessionFactory){ this.sqlSessionFactory = sqlSessionFactory; } @Override public User findUserByID(Serializable id){ SqlSession sqlSession = sqlSessionFactory.openSession(); User user = sqlSession.selectOne("test.findUserById",id); sqlSession.close(); return user; } @Override public List<User> findUsersByName(String name){ SqlSession sqlSession = sqlSessionFactory.openSession(); List<User> list = sqlSession.selectList("test.findUserByName",name); sqlSession.close(); return list; } }
Test.java
public class UserDaoTest{ private SqlSessionFactory sqlSessionFactory; private UserDao userDao; { String resource = "SqlMapConfig.xml"; InputStream is; try{ is = Resources.getResourceAsStream(resource); SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); sqlSessionFactory = builder.build(is); userDao = new UserDaoImpl(sqlSessionFactory); }catch(IOException e){ e.printStackTrace(); } } @Test public void testFindUserByID(){ User user = userDao.findUserByID(27); System.out.println(user); } @Test public void testFindUsersByName(){ List<User> list = userDao.findUsersByName("小明"); for(User user : list){ System.out.println(user); } } }
原始dao开发存在一些问题:
(1)存在一定量的模板代码
比如: 通过SqlSessionFactory创建SqlSession;调用SqlSession的方法操作数据库;关闭Sqlsession。
(2)存在一些硬编码
调用SqlSession的方法操作数据库时,需要指定statement的id,这里存在了硬编码。
Mapper代理的开发方式,程序员只需要编写mapper接口(相当于dao接口)即可。Mybatis会自动的为mapper接口生成动态代理实现类。不过要实现mapper代理的开发方式,需要遵循一些开发规范。
(1)mapper接口的全限定名要和mapper映射文件的namespace的值相同。
(2)mapper接口的方法名称要和mapper映射文件中的statement的id相同。
(3)mapper接口的方法参数只能有一个,且类型要和mapper映射文件中statement的parameterType的值保持一致。
(4)mapper接口的返回值类型要和mapper映射文件中statement的resultType值或resultMap中的type值保持一致。
Mapper.java
public interface UserMapper{ public User findUserById(int id); public void saveUser(User user); }
UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!-- namespace:此时用mapper代理方式,它的值必须等于对应mapper接口的全限定名 --> <mapper namespace="com.kiwi.mapper.UserMapper"> <!-- 根据ID查询一个用户 --> <select id="findUserById" parameterType="int" resultType="com.kiwi.domain.User"> SELECT * FROM USER WHERE id = #{id} </select> <!-- 根据名字模糊查询 --> <select id="findUserByName" parameterType="java.lang.String" resultType="com.kiwi.domain.User"> SELECT * FROM USER WHERE username LIKE ‘%${value}%‘ </select> <!-- 添加一个用户,并返回插入的ID --> <insert id="saveUser" parameterType="com.kiwi.domain.User"> <selectKey keyProperty="id" resultType="int" order="AFTER"> SELECT LAST_INSERT_ID() </selectKey> INSERT INTO USER (username,birthday,sex,address) values(#{username},#{birthday},#{sex},#{address}) </insert> <!-- 删除一个用户 --> <delete id="deleteUser" parameterType="int"> DELETE FROM USER WHERE id = #{id} </delete> <!-- 修改一个用户 --> <update id="updateUser" parameterType="com.kiwi.domain.User"> UPDATE USER SET username = #{username},address = #{address} WHERE id = #{id} </update> </mapper>
SqlMapConfig.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> <!-- 配置mybatis的环境信息,与spring整合之后,该部分将由spring管理 --> <environments default="development"> <environment id="development"> <!-- 配置JDBC事务控制,由mybatis进行管理 --> <transactionManager type="JDBC"></transactionManager> <!-- 配置数据源,采用dbcp连接池 --> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf8" /> <property name="username" value="root" /> <property name="password" value="123456" /> </dataSource> </environment> </environments> <!-- 加载Mapper --> <mappers> <mapper resource="mapper/UserMapper.xml"/> </mappers> </configuration>
Test.java
private SqlSessionFactory sqlSessionFactory; @Before public void setUp() throws Exception{ InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } @Test public void testFindUserById(){ SqlSession sqlSession = sqlSessionFactory.openSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = mapper.findUserById(26); System.out.println(user); sqlSession.close(); } @Test public void testSaveUser(){ SqlSession sqlSession = sqlSessionFactory.openSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); User user = new User("WWW","1",new Date(),"北京市海淀区"); mapper.saveUser(user); System.out.println(user); sqlSession.commit(); sqlSession.close(); } }
类别名,只能对PO类进行类型别名的定义。
别名 |
映射的类型 |
_byte |
byte |
_long |
long |
_short |
short |
_int |
int |
_integer |
int |
_double |
double |
_float |
float |
_boolean |
boolean |
string |
String |
byte |
Byte |
long |
Long |
short |
Short |
int |
Integer |
integer |
Integer |
double |
Double |
float |
Float |
boolean |
Boolean |
date |
Date |
decimal |
BigDecimal |
bigdecimal |
BigDecimal |
标签:
原文地址:http://www.cnblogs.com/yangang2013/p/5634316.html