Mybatis的Mapper代理方法和全域性配置檔案
阿新 • • 發佈:2019-02-12
package com.zucc.dao;
import com.zucc.model.User;
public interface UserMapper {
public void addUser(User user);
}
UserMapper.xmlUserService.jave<?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"> <mapper namespace="com.zucc.dao.UserMapper"> <resultMap type="User" id="UserMap"> <id property="id" column="uid"/> <result property="username" column="username"/> <result property="password" column="password"/> <result property="email" column="email"/> </resultMap> <select id="addUser" parameterType="User"> insert into user(username,password,email) values (#{username},#{password},#{email}) </select> </mapper>
package com.zucc.service; import java.io.IOException; import java.io.InputStream; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import com.zucc.dao.UserMapper; import com.zucc.model.User; public class UserService { SqlSession sqlSession = null; SqlSessionFactory sqlSessionFactory = null; UserMapper userMapper = null; public void before() { String resource = "SqlMapConfig.xml"; InputStream is = null; try { is = Resources.getResourceAsStream(resource); } catch (IOException e) { e.printStackTrace(); } SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder() .build(is); sqlSession = sqlSessionFactory.openSession(); userMapper = sqlSession.getMapper(UserMapper.class); } public boolean saveUser(User user) { before(); try { userMapper.addUser(user); sqlSession.commit(); } catch (Exception e) { sqlSession.close(); return false; } sqlSession.close(); return true; } }
總結:
以上開發規範主要是對下邊的程式碼進行統一生成:
sqlSession.insert("UserMapper.insertUser", user);
Mybatis的全域性配置檔案,配置內容如下:
properties(屬性)
settings(全域性配置引數)
typeAliases(類型別名)
mappers(對映器)
1.properties屬性
需求:將資料庫連線引數單獨配置在db.properties中,只需要在SqlMapConfig.xml中載入db.properties的屬性值。在SqlMapConfig.xml中就不需要對資料庫連線引數硬編碼。
將資料庫連線引數只配置在db.properties中,原因:方便對引數進行統一管理,其他xml可以引用該db.properties.