实现步骤:
1.导包
2.定义全局配置文件(核心配置文件)
*定义数据库连接信息(定义数据库连接池)
<---->
<properties resource="jdbc.properties"/>
<settings>
<setting name="logImpl" value="log4j"/>
</settings>
<typeAliases>
<package name="com.itheima.bean"/>
</typeAliases>
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
*加载SQQL映射文件
<mappers>
<mapper resource="映射文件名"/>
</mappers>
3编写SQL映射文件
<mapper namespace="dao.dao">
<select id="selects" resultType="domain.User" >
select * from user
</select>
<select id="select" resultType="domain.User" parameterType="int">
select * from user where id=#{id}
</select>
<insert id="insert" parameterType="domain.User" >
insert into user values (#{id},#{username},#{password})
</insert>
<update id="update" parameterType="domain.User">
update user set username=#{username},password=#{password} where id =#{id}
</update>
<delete id="delete" parameterType="int">
delete from user where id =#{int}
</delete>
</mapper>
4.编写Java代码
*加载配置文件
*获取SQLSession
public interface dao {
List<User> selects();
User select(int i);
Integer insert(User user);
Integer update(User user);
Integer delete(int i);
}
public List<User> selects() {
InputStream inp = null;
SqlSession sqlSession = null;
dao mapper = null;
try {
inp = Resources.getResourceAsStream("核心配置文件名称");
SqlSessionFactory build = new SqlSessionFactoryBuilder().build(inp);
sqlSession = build.openSession(true);
mapper = sqlSession.getMapper(dao.class);
} catch (IOException e) {
e.printStackTrace();
}
List<User> selects = mapper.selects();
try {
sqlSession.close();
inp.close();
} catch (IOException e) {
e.printStackTrace();
}
return selects;
}
SqlSessionFactory
openSession() : 创建SQLSession并且默认不会自动提交事务
openSession(bool): 如果bool为true事务自动提交
Mapper标签
属性: namespace, 理解为包名
mybatis 映射文件自动生成 dao层实现类:
namespace=“dao层类全路径”
增删改查标签id=“方法名”
增删改查标签
id :方法名
resultType: 返回值类型
parameterType: 参数类型
sql语句接受参数用#{参数名}