1.添加依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.32</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
2.编写核心配置文件和映射配置文件(注意文件头不同)
映射配置文件 以及增删改查标签
<?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">
<!--namespace任意取-->
<mapper namespace="userMapper">
<!--使用了别名配置-->
<select id="findAll" resultType="user">
select * from user
</select>
<!--插入-->
<!--参数名对应pojo类的属性-->
<insert id="save" parameterType="com.itheima.domain.User">
insert into user values(#{id},#{username},#{password})
</insert>
<!--修改操作-->
<update id="update" parameterType="com.itheima.domain.User">
update user set username=#{username},password=#{password} where id=#{id}
</update>
<!--删除-->
<!--参数名任意取-->
<delete id="delete" parameterType="java.lang.Integer">
delete from user where id=#{id}
</delete>
</mapper>
核心配置文件
<?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>
<!--加载properties文件-->
<properties resource="jdbc.properties"></properties>
<!--定义别名-->
<typeAliases>
<typeAlias type="com.itheima.domain.User" alias="user"/>
</typeAliases>
<!--数据源环境-->
<!--默认环境为developement-->
<environments default="developement">
<environment id="developement">
<!--配置事务管理器-->
<transactionManager type="JDBC"></transactionManager>
<!--配置数据源 这里使用POOLED池化方式-->
<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>
<!--加载映射文件-->
<mappers>
<mapper resource="com/itheima/mapper/UserMapper.xml"/>
</mappers>
</configuration>
3.编写测试 查询 添加(需要提交事务)
@Test
public void test1() throws IOException {
//获得核心配置文件
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
//获得session工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
//获得session会话对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//执行操作 参数:namespace + id
List<User> userlist = sqlSession.selectList("userMapper.findAll");
System.out.println(userlist);
//释放资源
sqlSession.close();
}
@Test
public void test2() throws IOException {
//获得核心配置文件
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
//获得session工厂对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
//获得session会话对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//执行操作 参数:namespace + id
User user=new User();
user.setUsername("fanglei");
user.setPassword("123");
sqlSession.insert("userMapper.save",user);
//mybatis默认事务不提交
sqlSession.commit();
//释放资源
sqlSession.close();
}
目录结构