如何使用mybatis
使用mybatis可以将sql语句与java代码分离,便于后期维护或修改
准备阶段
a、下载MyBatis相应jar包
b、创建Java工程,导入MyBatis jar包(mybatis-3.4.4.jar)和数据库驱动包
c、创建user_info表并添加数据
使用
a.创建名为mybatis-conf.xml的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>
<environments default="dev">
<environment id="dev">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="username" value="root"/>
<property name="password" value="root"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/test"/>
<property name="driver" value="com.mysql.jdbc.Driver"/>
</dataSource>
</environment>
<environment id="test">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="username" value="root"/>
<property name="password" value="root"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/test"/>
<property name="driver" value="com.mysql.jdbc.Driver"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="area.xml"/>
</mappers>
</configuration>
b.创建名为area.xml的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">
<mapper namespace="com.jd.area.IAreaDao">
<select id="getName" resultType="java.lang.String">
select user_name from user_info where id=#{id} and password=#{code}
</select>
<delete id="delete" >
delete from user_info where id=#{id}
</delete>
<insert id="insert">
insert into user_info (id,user_name,password) values(#{id},#{name},#{code})
</insert>
<update id="update">
update user_info set user_name=#{name},password=#{code} where id=#{id}
</update>
</mapper>
c.创建接口
package com.jd.area;
import com.jd.vo.Area;
import org.apache.ibatis.annotations.Param;
public interface IAreaDao {
String getName(@Param("id") String id, @Param("password") String code);
boolean delete(@Param("id") String id);
boolean insert(Area area);
boolean update(Area area);
}
d.创建测试类Test
package com.jd.test;
import com.jd.area.IAreaDao;
import com.jd.vo.Area;
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 java.io.InputStream;
public class Test {
public static void main(String[] args) {
try{
InputStream inputStream = Resources.getResourceAsStream("mybatis-conf.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = factory.openSession(true);
IAreaDao areaDao = session.getMapper(com.jd.area.IAreaDao.class);
System.out.println(areaDao.getName("001"));
session.close();
}catch(Exception e){
e.printStackTrace();
}
}
}