步骤一
先新建一个Project mybatis.
在src里建一个包com.zhongruan
在zhongruan里面建一个bean,dao,test包
在web下建立一个lib文件夹,将需要用的jar包都导入
源代码
UserMpper1.xml
<?xml version="1.0" encoding="UTF-8"?> select * from tb_user<delete id="deleteById">
delete from tb_user where id=#{id}
</delete>
<update id="updateById" parameterType="com.zhongruan.bean.User">
update tb_user set username=#{username},password=#{password} where id=#{id}
</update>
<insert id="addById" parameterType="com.zhongruan.bean.User">
insert into tb_user(username,password) values (#{username},#{password})
</insert>
IUserDao
package com.zhongruan.dao;
import com.zhongruan.bean.User;
import java.util.List;
public interface IUserDao {
List findAll();
void deleteById(int id);
void updateById(User user);
void addById();
}
sqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8" ?></environments>
<mappers>
<mapper resource="com/zhongruan/dao/UserMapper1.xml"></mapper>
</mappers>
User.java
package com.zhongruan.bean;
public class User {
private int id;
private String username;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
Test.java
package com.zhongruan.test;
import com.zhongruan.bean.User;
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.IOException;
import java.io.Reader;
import java.util.List;
public class Test {
public static void main(String[] args) throws IOException {
Reader reader=Resources.getResourceAsReader(“sqlMapConfig.xml”);
SqlSessionFactory build=new SqlSessionFactoryBuilder().build(reader);
SqlSession session=build.openSession();
// List users=session.selectList(“findAll”); 查询
// System.out.println(users);
// session.delete(“deleteById”,18);//删除
// session.commit();
// session.close();
// User user=new User(); //修改
// user.setId(21);
// user.setUsername(“sdf”);
// user.setPassword(“sdfs”);
// session.update(“updateById”,user);
// session.commit();
// session.close();
User user=new User();//增添
user.setUsername("sfd");
user.setPassword("fs");
session.insert("addById",user);
session.commit();
session.close();
}
}