<?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>
<typeAliases>
<typeAlias alias="User" type="com.lin.model.User" />
</typeAliases>
<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/dang?useUincode=true&characterEncoding=utf8" />
<property name="username" value="root" />
<property name="password" value="123456" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/lin/dao/UserDao.xml" />
</mappers>
</configuration>
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">
<mapper namespace="com.lin.dao.UserDao">
<resultMap type="User" id="foo">
<id property="id" column="id" />
<result property="username" column="username" />
<result property="password" column="password" />
<result property="email" column="email" />
<result property="nickname" column="nickname" />
<result property="gender" column="gender"/>
<result property="photo" column="photo"/>
</resultMap>
<select id="findAll" resultMap="foo">
select * from tb_user
</select>
<select id="findById" parameterType="String" resultType="User">
select * from tb_user where username=#{username}
</select>
<insert id="save" parameterType="User">
insert into tb_user values (default,#{username},#{password},#{email},#{gender},#{nickname},#{photo})
</insert>
<delete id="deleteByUsername" parameterType="String">
delete from tb_user where username=#{username}
</delete>
<update id="update" parameterType="User">
update tb_user set password=#{password} where username=#{username}
</update>
</mapper>
3.package com.lin;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.function.Supplier;
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 com.lin.dao.UserDao;
import com.lin.model.User;
/**
- Unit test for simple App.
*/
public class AppTest {
public static void main(String[] args) throws IOException {
//通过输入流 读取配置文件
InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
//建立sql会话工厂
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
SqlSession session = factory.openSession();
UserDao userDao = session.getMapper(UserDao.class);
// List<User> userList = userDao.findAll();
// for (User user : userList) {
// System.out.println(user.getUsername());
// }
User user = new User();
user.setUsername("admin");
user.setPassword("123123");
userDao.update(user);
session.commit();
}
}