sqlMapConfig.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="development">
<environment id="development">
<!--事务管理-->
<transactionManager type="JDBC"></transactionManager>
<!--连接池-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/jdbc?characterEncoding=utf-8"></property>
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/zhongruan/dao/UserMapper1.xml"></mapper>
</mappers>
</configuration>
jdbc的sql语句
<?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.zhongruan.dao.IUserdao">
<select id="findAll" resultType="com.zhongruan.bean.User">
select * from user;
</select>
<delete id="deleteById" parameterType="int">
delete from user where id=#{id};
</delete>
<update id="updateById" parameterType="com.zhongruan.bean.User">
update user set password=#{password} where id=#{id};
</update>
<insert id="insert" parameterType="com.zhongruan.bean.User">
insert into user(password,type) values(#{password},1);
</insert>
</mapper>
Bean中User属性
public class User {
private int id;
private String password;
private String type;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", password='" + password + '\'' +
", type='" + type + '\'' +
'}';
}
}
dao包中的代码
public interface IUserdao {
List<User> findAll();
void deleteById(int id);
void updateById(User user);
void insert(User user);
}
写个Test测试文件
public class Test {
public static void main(String[] args) throws IOException {
Reader resourceAsReader = Resources.getResourceAsReader("sqlMapConfig.xml");
SqlSessionFactory build=new SqlSessionFactoryBuilder().build(resourceAsReader);
SqlSession session=build.openSession();
List<User> userList=session.selectList("findAll");
User user=new User();
user.setId(4);
user.setPassword("777");
session.delete("deleteById",5);
session.update("updateById",user);
User user1=new User();
user1.setPassword("987");
session.insert("insert",user1);
System.out.println(userList);
session.commit();
session.close();
}
}