Mybatis增删改查,Demo整合

时间:2024-03-24 15:04:44

第一步:MyBatis的Jar包引入
mybatis-3.2.7.jar
mysql-connector-java-5.1.8.jar

MyBatis的pom.xml依赖

    <dependencies>
<!-- jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency> <!-- servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.</version>
<scope>provided</scope>
</dependency> <!-- junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency> <!-- mybatis依赖 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.</version>
</dependency> <!-- mysql-connector-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.</version>
</dependency>
</dependencies> <build>
<plugins>
<!-- JDK配置 -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-</encoding>
</configuration>
</plugin> <!-- Tomcat配置 -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<configuration>
<port></port>
<path>/</path>
</configuration>
</plugin>
</plugins>
</build>

  

第二步:引入log4j.properties日志文件

# Global logging configuration
log4j.rootLogger=DEBUG, stdout # Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

第三步:创建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"> <!-- MyBatis的配置文件信息 -->
<configuration>
<!-- 和spring整合后 environments配置将废除 -->
<environments default="development">
<environment id="development">
   <!-- 使用jdbc事务管理 -->
  <transactionManager type="JDBC"></transactionManager>
  <!-- 数据库连接池 -->
  <dataSource type="POOLED">
   <property name="driver" value="com.mysql.jdbc.Driver" />
   <property name="url" value="jdbc:mysql://localhost:3306/test06?characterEncoding=utf-8" />
   <property name="username" value="root" />
   <property name="password" value="root" />
  </dataSource>
</environment>
</environments> <!-- 加载mapper映射文件 -->
<mappers>
<mapper resource="com/baidu/mapper/UserMapper.xml"/>
</mappers>
</configuration>

第四步:创建用户实体类User类

/**
* 用户实体类
* @author Administrator
*/
public class User {
private int id;
private String name;// 用户姓名
private Date birthday;// 生日
private char sex;// 性别
private String address;// 地址 public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public char getSex() {
return sex;
}
public void setSex(char sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public User(int id, String name, Date birthday, char sex, String address) {
super();
this.id = id;
this.name = name;
this.birthday = birthday;
this.sex = sex;
this.address = address;
}
public User() {
super();
// TODO Auto-generated constructor stub
} @Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", birthday=" + birthday + ", sex=" + sex + ", address=" + address
+ "]";
}
}

第五步:创建User实体类的映射文件UserMapper.xml

<?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:命名空间,用于隔离sql, 命名空间 user.findUserById-->
<mapper namespace="user">

    增删改查SQL语句
</mapper>

第六步:MyBatis的测试类

/**
* 测试类
* @author Administrator
*
*/
public class MybatisTest1 {
public static void main(String[] args) throws Exception {
//加载MyBatis的核心配置文件
String resource = "sqlMapConfig.xml";
//获取输入流
InputStream resourceAsStream = Resources.getResourceAsStream(resource);
//创建sqlSessionFactory工厂
SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(resourceAsStream);
//创建sqlSession
SqlSession session = sf.openSession(); //执行增删改查SQL语句
} }
增删改查SQL语句&&执行增删改查SQL语句
  • 通过ID查询一个用户
    •  <!-- 通过ID查询一个用户
      id名字,namespace+id用来定位具体的sql
      parameterType: 指定输入参数类型
      resultType:返回值,指定sql输出结果的所映射的java对象类型,如果bean与数据库一一对应,则会自动映射
      where id=#{v},#{} 占位符,里面要写一个任意字符
      -->
      <select id="findUserById" parameterType="Integer" resultType="com.mqf.entity.User">
      <!-- 如果用${value}传参,默认没有单引号,如果用#{id}传参,默认带有单引号 -->
      SELECT * FROM tb_user WHERE id = #{id};
      </select>
    •  //执行sql语句(查询单条数据方法1)
      User user = session.selectOne("user.findUserById",1);
      System.out.println(user+"==========================");

        

  • 全查询
      • <!-- 全查询 -->
        <select id="selectAllUser" resultType="com.mqf.entity.User">
        SELECT * FROM tb_user;
        </select>
      • //全查询
        List<User> list = session.selectList("user.selectAllUser");
        if (list.size()>0 && null!=list){
        for (User user1 :list){
        System.out.println(user1+"==========================");
        //关闭连接
        session.close();
        }
        }else{
        System.out.println("查询异常!");
        }*/
  • 模糊查询
      • <!--模糊查询-->
        <!-- 根据名字模糊查询
        #{} 1.相当于? =='' 会带单引号 2.里面的表示字符任意
        ${} 1.不带单引号 2.里面的字符必须为value
        resultType="com.ali.pojo.User" 写的是list的泛型
        -->
        <select id="selectUserName" parameterType="String" resultType="com.mqf.entity.User">
        <!-- select * from t_user where name like "%"#{name}"%"-->
        SELECT * FROM tb_user where name like '%${value}%'
        </select>
      • //模糊查询
        /* List<User> list = session.selectList("user.selectUserName", "一");
        System.out.println(list+"======================================");*/
  • 添加用户信息
      • <!-- 添加用户信息 -->
        <insert id="insertUser" parameterType="com.mqf.entity.User" useGeneratedKeys="true" keyProperty="id">
        /*
        将插入数据的主键,返回到user对象中
        SELECT LAST_INSERT_ID(); 得到下面insert进去记录的主键值,只适用于主键自增 keyProperty:将查询到主键值设置到parameterType指定的对象的id属性
        order: SELECT LAST_INSERT_ID();执行顺序,相对于insert语句来说它的执行顺序之后
        resultType:指定 SELECT LAST_INSERT_ID();的结果类型
        */
        /*
        使用mysql的uuid()生成主键
        执行过程:
        首先通过uuid()得到主键,将主键设置到user对象的id属性中
        其次在insert执行时,从user对象中取出id属性值
        <selectKey keyProperty="id" order="BEFORE" resultType="Integer">
        SELECT uuid();
        </selectKey>
        INSERT INTO tb_user SET id = {id},name = #{name},birthday = #{birthday},sex = #{sex},address = #{address};
        */
        <selectKey keyProperty="id" order="AFTER" resultType="Integer">
        SELECT LAST_INSERT_ID();
        </selectKey>
        INSERT INTO tb_user SET name = #{name},birthday = #{birthday},sex = #{sex},address = #{address};
        </insert>
      • //添加用户信息
        //第一步:实例化对象
        /* User user1 = new User();
        user1.setName("锡纸烫");
        user1.setSex('男');
        user1.setBirthday(new Date());
        user1.setAddress("河南安阳");
        //第二步:要session操作sql语句
        int i = session.insert("user.insertUser", user1);
        //第三步:事务提交
        session.commit();
        //判断返回值
        if (i > 0) {
        System.out.println("添加成功!");
        System.out.println(user1.getId()+"====================");
        }else {
        System.out.println("添加失败!");
        }*/
  • 添加用户信息 (批量)
      • <!-- 添加用户信息 (批量)-->
        <insert id="insertUsers" parameterType="List">
        INSERT INTO tb_user(name,birthday,sex,address) VALUES
        <foreach collection="list" item="user" index="index" separator=",">
        (#{user.name},#{user.birthday},#{user.sex},#{user.address});
        </foreach>
        </insert>
      •  /**
        * 批量添加用户信息
        */
        /* User user1 = new User();
        user1.setName("Duck");
        user1.setBirthday(new Date());
        user1.setSex('男');
        user1.setAddress("郑州"); User user2 = new User();
        user2.setName("Duck");
        user2.setBirthday(new Date());
        user2.setSex('男');
        user2.setAddress("郑州"); List<User> list = new ArrayList<>();
        list.add(user1);
        list.add(user2); System.out.println(list+"+================");
        int i = session.insert("user.insertUsers", list);
        //提交事务
        session.commit(); if (i>0) {
        System.out.println("添加成功!");
        //关闭连接
        session.close();
        }else {
        System.out.println("添加失败!");
        //关闭连接
        session.close();
        }*/
  • 添加用户信息并返回添加用户主键id
      • <!-- 添加用户信息并返回添加用户主键id -->
        <insert id="insertUser" parameterType="com.mqf.entity.User" useGeneratedKeys="true" keyProperty="id">
        INSERT INTO tb_user SET name = #{name},birthday = #{birthday},sex =#{sex},address = #{address};
        </insert>
      • /**
        * 添加用户信息并返回添加用户主键id
        */
        User user1 = new User();
        user1.setName("Duck1");
        user1.setBirthday(new Date());
        user1.setSex('男');
        user1.setAddress("郑州");
        int i = session.insert("user.insertUser", user1);
        //提交事务
        session.commit(); if (i>0) {
        System.out.println("添加成功!");
        System.err.println(user1.getId()+"==========================");
        //关闭连接
        session.close();
        }else {
        System.out.println("添加失败!");
        //关闭连接
        session.close();
        }
  • 删除用户信息(单删)
      • <!--删除用户信息(单删)-->
        <delete id="deleteUserById" parameterType="com.mqf.entity.User">
        delete from tb_user where id = #{id};
        </delete>
      • //删除用户信息(单删)
        /* int delete = session.delete("user.deleteUserById", 2);
        System.out.println(delete+"===================================");*/
  • 删除用户信息(批删)
      • <!--删除用户信息(批删)-->
        <delete id="deleteUserByIds" parameterType="int[]" >
        DELETE FROM tb_user WHERE id IN
        <!-- collection一般用到的值array、list、map。。。-->
        <foreach collection="array" item="array" index="no" open="(" separator="," close=")">
        #{array}
        </foreach>
        </delete>
      • //删除用户信息(批删)
        /*int[] array = {3,4};
        int i = session.delete("user.deleteUserByIds", array);
        //提交事务
        session.commit();
        if (i > 0) {
        System.out.println("删除成功!");
        //关闭连接
        session.close();
        }else {
        System.out.println("删除失败!");
        //关闭连接
        session.close();
        }*/
  • 修改用户信息  
      • <!--修改用户信息-->
        <update id="updataUserById" parameterType="List" >
        update tb_user set name = #{name} where id = #{id};
        </update>
      • //修改用户信息
        //第一步,实例化对象
        /*User user2 = new User();
        user2.setId(1);
        user2.setName("李二蛋");
        //第二步,执行修改
        int update = session.update("user.updataUserById", user2);
        //第三步,提交事务
        session.commit();
        if (update>0) {
        System.out.println("修改成功!");
        //关闭连接
        session.close();
        }else {
        System.out.println("修改失败!");
        //关闭连接
        session.close();
        }*/

以上就是简单增删改查的总结的小项目。