mybatis概念
概念:一個(gè)持久層框架
作用:ORM將sql語句映射成實(shí)體類
特點(diǎn):
巧靈活
半自動(dòng)化
使用與中小型項(xiàng)目的開發(fā)
mybatis入門
1、創(chuàng)建mybatis-config.xml文件
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/bank?useUnicode=true&characterEncoding=utf-8"/>
<property name="username" value="root"/>
<property name="password" value=""/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="UserMapper.xml"/>
</mappers>
</configuration>
2穷娱、創(chuàng)建映射文件UserMapper.xml
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="user">
<select id="selectUser" resultType="com.hemi.mybatis.bean.User">
select * from user where uid=1;
</select>
</mapper>
3、獲取xml配置文件
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
4蛔垢、創(chuàng)建SqlSessionFactory
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(inputStream);
5击孩、獲取SqlSession
SqlSession sqlSession = factory.openSession();
6迫悠、調(diào)用SqlSession的selectOne(命名空間.id名稱);
Object object = sqlSession.selectOne("user.selectUser");
7、關(guān)閉SqlSession
sqlSession.close();
增刪改
增
Some_Text
<insert id="insertUser" parameterType="com.hemi.mybatis.bean.User">
insert into user (username,password) values(#{username},#{password});
</insert>
改
<update id="updateUser" parameterType="com.hemi.mybatis.bean.User">
update user set username=#{username},password=#{password} where uid=#{uid}
</update>
刪
Some_Text
<delete id="deleteUser" parameterType="int">
delete from user where uid=#{value}
</delete>
Mapper接口開發(fā)
一巩梢、定義一個(gè)接口
public interface TypeMapper {
Type selectType(int typeid);
}
二创泄、定義一個(gè)mapper.xml映射文件
mapper文件的要求:
namespace的值就是對(duì)象接口的全類名,并且類名和xml文件名保持一致
id的值就是抽象方法
resultType的值必須和抽象方法的返回值一致
parameterType的值和抽象方法的參數(shù)類型一致
注意 mapper.xml文件的約束是mapper.dtd括蝠,不是config.dtd
三鞠抑、使用
將mybatis入門步驟中的步驟六改為如下代碼:
TypeMapper mapper=sqlSession.getMapper(TypeMapper.class);
Type type=mapper.selectType(1);