Mybatis系列文章(1)
一:Mybatis主要做的工作
1 应用程序找Mybatis要数据(若这个类为Category)
2. mybatis从数据库中找来数据
2.1 通过mybatis-config.xml 定位哪个数据库
2.2 通过Category.xml执行对应的select语句
2.3 基于Category.xml把返回的数据库记录封装在Category对象中
2.4 把多个Category对象装在一个Category集合中
3. 返回一个Category集合
二:Mybatis第一个案例,查询所有
1.在pom.xml中添加依赖
2.在resources文件夹中配置SqlMapConfig.xml文件
3.创建log4j.properties文件以便打印日志信息
4.创建IUserDao接口,以及需要用到的User类—与表中user对应
5.在resources文件夹中创建与IUserDao接口对应的IUserDao.xml文件(要一个文件夹一个文件夹的添加不然识别不了)以便添加sql语句
6.在SqlMapConfig.xml中添加IUserDao.xml文件位置,让数据库是他发来的信息
7.使用代码
private InputStream in;
private SqlSession session;
private IUserDao userDao;
@Before
public void init() throws Exception
{
in= Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder();
SqlSessionFactory factory=builder.build(in);
session=factory.openSession();
userDao=session.getMapper(IUserDao.class);
}
@After
public void iclose() throws Exception
{
//注意,这里提交事务很重要,不提交的话,crud语句就无效了
session.commit();
session.close();
in.close();
}
这里就是将操作数据库的事情全部交给mybatis,于是现在就可以通过userDao来进行数据库操作了
三:CRUD操作
1.查询的sql语句为
select * from user
对应IUserDao.xml的语句为
<select id="findAll" resultType="com.itheima.domain.User">
select * from user
</select>
resultType 对应返回类型,id对应接口中的方法
2.插入的sql语句为
INSERT INTO table_name ( field1, field2,…fieldN )
VALUES
( value1, value2,…valueN );
对应IUserDao.xml的语句为
<insert id="saveUser" parameterType="com.itheima.domain.User">
insert into user(username,address,sex,birthday)values(#{username},#{address},#{sex},#{birthday})
</insert>
注意在这里values(#{username},#{address},#{sex},#{birthday})的取值要与User类中相同
否则会报错
3.更新sql语句为
UPDATE table_name SET field1=new-value1, field2=new-value2
[WHERE Clause]
对应IUserDao.xml的语句为
<update id="updateUser" parameterType="com.itheima.domain.User">
update user set username=#{username},address=#{address},sex=#{sex},birthday=#{birthday} where id=#{id}
</update>
与插入语句类似,必须保证不出错
4.删除数据的sql语句为
DELETE FROM table_name [WHERE Clause]
对应IUserDao.xml的语句为
<delete id="deleteUser" parameterType="java.lang.Integer">
delete from user where id=#{id}
</delete>
5.根据id查询某一行的sql语句
<select id="findById" parameterType="java.lang.Integer" resultType="com.itheima.domain.User">
select * from user where id = #{id}
</select>