Mybatis把访问数据库的操作都封装起来了,所以当我们使用Mybatis进行数据库操作时,只需要提供SQL语句就可以了,代码的逻辑会变得非常清晰,书写起来也很简洁。
下面的例子都是基于
一、create操作
在user.xml文件中添加
insert into user (user_name, user_id, user_pwd, user_phone) values(#{user_name}, #{user_id}, #{user_pwd}, #{user_phone} ) 复制代码
代码中添加:
User user = new User();user.setUser_name("Eve");user.setUser_id("12345");user.setUser_phone("13978992134");user.setUser_pwd("1111111");session.insert("addUser", user);session.commit();session.close();复制代码
二、算了,CURD没啥好写的,把代码贴在这吧
user.xml
复制代码 insert into user (user_name, user_id, user_pwd, user_phone) values(#{user_name}, #{user_id}, #{user_pwd}, #{user_phone} ) delete from user where user_id= #{user_id} update user set name=#{user_name} where id=#{user_id}
Test.java
import java.io.IOException;import java.io.InputStream;import java.util.List;import com.learn.pojo.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;public class Test { public static void main(String[] args) throws IOException { //声明配置文件地址 String resource = "mybatis-config.xml"; //得到输入流 InputStream inputStream = Resources.getResourceAsStream(resource); //创建sql会话工厂 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //打开sql会话 SqlSession session = sqlSessionFactory.openSession(); //获取查询结果 Listlu = session.selectList("listUser"); for (User u : lu) { System.out.println(u.getUser_name()); System.out.println(u.getUser_id()); System.out.println(u.getUser_phone()); System.out.println("------------------------"); } //创建User对象 User user = new User(); user.setUser_name("Eve"); user.setUser_id("12345"); user.setUser_phone("13978992134"); user.setUser_pwd("1111111"); //插入记录 session.insert("addUser", user); //删除记录 session.delete("deleteUser", user); //根据id选记录 User newUserr = session.selectOne("getUser","10086"); //更新记录 user.setUser_name("改过名的Eve"); session.update("updateUser",user); session.commit(); session.close(); }}复制代码