mybaitsdemo

studentDao

package com.qcby.dao;

import com.qcby.entity.student;

import java.util.List;

public interface studentDao {
    List<student> findAll();


}

UserDao

package com.qcby.dao;

import com.qcby.entity.User;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface UserDao {
    List<User> findAll();

    User findById(Integer id);

    /**
     * 数据的插入
     * @param user
     * @return
     */
    int insert(User user);

    /**
     * 获取插入数据的id
     * @param user
     * @return
     */
    int insertGetId(User user);

    /**
     * 根据id进行删除
     * @param id
     * @return
     */
    int delete(Integer id);

    /**
     * 数据的修改
     * @param user
     * @return
     */
    int update(User user);

    List<User> selectUserByUsernameAndSex(User user);

    List<User> updateByDo(User user);

    List<User> selectUserByChoose(User user);

    int deleteMoreByArray(@Param("ids") Integer[] ids);

    int insertMoreList(@Param("users") List<User> users);

}

student

package com.qcby.entity;

public class student {
    private Integer id;
    private String username;
    private String phone;
    private String sex;
    private String age;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }


    @Override
    public String toString() {
        return "student{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", phone='" + phone + '\'' +
                ", sex='" + sex + '\'' +
                ", age='" + age + '\'' +
                '}';
    }
}

User

package com.qcby.entity;
import java.util.Date;
public class User {
    private Integer id;
    private String username;
    private Date birthday;
    private String sex;
    private String address;


    public User(){

    }
    public  User(String username,String address){
        this.username = username;
        this.address = address;
    }


    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "user{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", birthday=" + birthday +
                ", sex='" + sex + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

studentDao.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" >

<mapper namespace="com.qcby.dao.studentDao">
    <select id="findAll" resultType="com.qcby.entity.student">
        select * from student;
    </select>
</mapper>

UserDao.xml

<?xml version="1.0" encoding="GBK"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >

<mapper namespace="com.qcby.dao.UserDao">

<!--    <resultMap id="result-map" type="com.qcby.entity.User">-->
<!--        <id column="id" property="id"></id>-->
<!--        <result column="username" property="username"></result>-->
<!--        <result column="birthday" property="birthday"></result>-->
<!--        <result column="sex" property="sex"></result>-->
<!--        <result column="address" property="address"></result>-->
<!--    </resultMap>-->
    <select id="findAll" resultType="com.qcby.entity.User" parameterType="java.lang.Integer">
        select * from user
        <where>
            <if test="username !=null and username != '' ">
                username = #{username}
            </if>
            <if test="sex != null and sex != '' ">
                and sex = #{sex}
            </if>
        </where>
    </select>
    <select id="findById" resultType="com.qcby.entity.User" parameterType="com.qcby.entity.User">
        select * from user where id = #{id}
    </select>

    <insert id="insert" parameterType="com.qcby.entity.User">
        insert into user (username,birthday,sex,address) values (#{username},#{birthday},#{sex},#{address})
    </insert>

    <insert id="insertGetId" parameterType="com.qcby.entity.User">
        <selectKey keyProperty="id" resultType="int" order="AFTER">
            SELECT  LAST_INSERT_ID()
        </selectKey>
        insert into user (username,birthday,sex,address) values (#{username},#{birthday},#{sex},#{address})
    </insert>

    <delete id="delete" parameterType="java.lang.Integer">
        delete from user where id = #{id}
    </delete>

    <update id="update" parameterType="com.qcby.entity.User">
        update user set username = #{username},birthday=#{birthday},
                        sex=#{sex},address=#{address} where id= #{id}
    </update>

    <select id="selectUserByUsernameAndSex" parameterType="com.qcby.entity.User" resultType="com.qcby.entity.User">

        select * from user
        <where>
            <if test="username != null">
                username=#{username}
            </if>
            <if test="sex != null">
                and sex=#{sex}
            </if>
        </where>
    </select>

    <update id="updateByDo" parameterType="com.qcby.entity.User">
        update user
        <set>
<!--            <if test="username !=null and username != '' ">-->
<!--                username = #{username}-->
<!--            </if>-->
<!--            <if test="address != null and username != '' ">-->
<!--                address = #{address}-->
<!--            </if>-->
<!--            <if test="birthday != null and birthday !='' ">-->
<!--                birthday = #{birthday}-->
<!--            </if>-->
<!--            <if test="sex != null and sex !='' ">-->
<!--                sex = #{sex}-->
<!--            </if>-->
            <trim prefix="set" prefixOverrides=",">
                <if test="username !=null and username != '' " >
                    username = #{username}
                </if>
                <if test="address !=null and username !=''">
                    address = #{address}
                </if>
                <if test="birthday != null and birthday != ''">
                    birthday = #{birthday}
                </if>
                <if test="sex != null and sex != ''">
                    sex = #{sex}
                </if>
            </trim>
        </set>
        where id = #{id}
    </update>


    <select id="selectUserByChoose" resultType="com.qcby.entity.User" parameterType="com.qcby.entity.User">
        select * from user
        <where>
            <choose>
                <when test="id !='' and id != null ">
                    id = #{id}
                </when>
                <when test="username != '' and username != null ">
                    and username = #{username}
                </when>
                <otherwise>
                    and sex = #{sex}
                </otherwise>
            </choose>

        </where>
    </select>

    <delete id="deleteMoreByArray">
        delete from user where id in
        <foreach collection="ids" item="id" open="(" close=")" separator=",">
            #{id}
        </foreach>
    </delete>

    <insert id="insertMoreList">
        INSERT into user values
        <foreach collection="users" item="user" separator=",">
            (null,#{user.username},null ,null,#{user.address})
        </foreach>
    </insert>

</mapper>

SqlMapConfig.xml

<?xml version="1.0" encoding="GBK"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <environments default="mysql">
        <environment id="mysql">
            <!--配置事务的类型,使用本地事务策略-->
            <transactionManager type="JDBC"></transactionManager>
            <!--是否使用连接池 POOLED表示使用链接池,UNPOOLED表示不使用连接池-->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis_demo?useUnicode=true&amp;characterEncoding=utf8"/>
                <property name="username" value="root"/>
                <property name="password" value="2020"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="mapper/studentDao.xml"></mapper>
        <mapper resource="mapper/UserDao.xml"></mapper>
    </mappers>
</configuration>

studentTest

package com.test;
import com.qcby.dao.studentDao;
import com.qcby.entity.User;
import com.qcby.entity.student;
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 org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class studentTest {

    private InputStream in = null;
    private SqlSession session = null;
    private studentDao mapper = null;

    @Before
    public void init() throws IOException {
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        session = factory.openSession();
        mapper = session.getMapper(studentDao.class);
    }

    @After
    public void destory() throws IOException {
        session.close();
        in.close();
    }
    @Test
    public void findAll(){
        List<student> all = mapper.findAll();
        for (student s:all){
            System.out.println(s.toString());
        }
    }

}

UserTest

package com.test;
import com.qcby.dao.UserDao;
import com.qcby.entity.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 org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

public class UserTest {

    private InputStream in = null;
    private SqlSession session = null;
    private UserDao mapper = null;

    @Before  //前置通知, 在方法执行之前执行
    public void init() throws IOException {
        //加载主配置文件,目的是为了构建SqlSessionFactory对象
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //创建SqlSessionFactory对象
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //通过SqlSessionFactory工厂对象创建SqlSesssion对象
        session = factory.openSession();
        //通过Session创建UserDao接口代理对象
        mapper = session.getMapper(UserDao.class);
    }

    @After  //@After: 后置通知, 在方法执行之后执行 。
    public void destory() throws IOException {
        //释放资源
        session.close();
        in.close();
    }
    @Test
    public void find(){
        List<User> users = mapper.findAll();
        for (User user:users){
            System.out.println(user.toString());
        }
    }

    @Test
    public void findById(){
        User user = mapper.findById(1);
        System.out.println(user.toString());
    }



    @Test
    public void insert(){
        User user = new User();
        user.setUsername("界徐盛");
        user.setBirthday(new Date());
        user.setAddress("三国杀");
        user.setSex("男");
        int code = mapper.insert(user);
        session.commit();
        System.out.println(code);
    }

    @Test
    public void insertGetId(){
        User user = new User();
        user.setUsername("张四");
        user.setBirthday(new Date());
        user.setAddress("保定");
        user.setSex("男");
        int code =  mapper.insertGetId(user);
        //数据修改:需要做session提交
        session.commit();
        System.out.println(code);
        //输出我们的新插入数据在数据库当中的id值
        System.out.println(user.getId());
    }


    @Test
    public void delete(){
        int code =  mapper.delete(7);
        session.commit();
        System.out.println(code);
    }

    @Test
    public void update(){
        User user = new User();
        user.setId(6);
        user.setUsername("李四");
        user.setBirthday(new Date());
        user.setAddress("保定");
        user.setSex("男");
        int code = mapper.update(user);
        session.commit();
        System.out.println(code);
    }

    @Test
    public void selectUserByUsernameAndSex(){
        User user1 = new User();
        user1.setUsername("熊大");
        List<User> users = mapper.selectUserByUsernameAndSex(user1);
        for(User user:users){
            System.out.println(user.toString());
        }
    }
    @Test
    public void updateByDo(){
        User user = new User();
        user.setId(4);
        user.setUsername("李四");
        user.setBirthday(new Date());
        user.setAddress("保定");
        user.setSex("男");
        int code = mapper.update(user);
        session.commit();
        System.out.println(code);
    }
    @Test
    public void selectUserByChoose(){
        User user1 = new User();
        user1.setSex("男");
        List<User> users = mapper.selectUserByChoose(user1);
        for (User user:users) {
            System.out.println(user.toString());
        }
    }
    @Test
    public void deleteMoreByArray(){
        Integer[] ids = new Integer[]{1,2,3};
        int count = mapper.deleteMoreByArray(ids);
        session.commit();
        System.out.println(count);
    }
    @Test
    public void insertMoreList(){
        User user1 = new User("a","上海");
        User user2 = new User("b","北京");
        User user3 = new User("c","天津");
        List<User> users = Arrays.asList(user2, user1, user3) ;
        int count = mapper . insertMoreList(users);
        session.commit() ;
        System.out.println(count);
    }

}

pom.xml

<?xml version="1.0" encoding="GBK"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.qcby</groupId>
    <artifactId>mybatisdemo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>GBK</project.build.sourceEncoding> <project.reporting.outputEncoding>GBK</project.reporting.outputEncoding> <maven.compiler.encoding>GBK</maven.compiler.encoding>


    </properties>
    <build>
        <plugins>
        <!-- 指定jdk,防止update project -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
                <!-- 项目编码-->
                <encoding>UTF-8</encoding>
            </configuration>
        </plugin>
        </plugins>
    </build>
    <dependencies>
        <!--mybatis核心包-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>
        <!--mysql驱动包-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        <!-- 单元测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
        </dependency>
        <!-- 日志 -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>
</project>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值