动力节点首页 全国咨询热线:400-8080-105

绑定手机号,登录
手机号

验证码

微信登录
手机号登录
手机号

验证码

微信登录与注册
微信扫码登录与注册

扫码关注微信公众号完成登录与注册
手机号登录
首页 > 文章

MyBatis查询方法

07-15 11:05 757浏览
举报 T字号
  • 大字
  • 中字
  • 小字

User.java

package com.mycom.mybatis_1.bean;
import java.io.Serializable;
public class User implements Serializable {
    /**
     * 
     */
    private static final long serialVersionUID = 7273023435058492423L;
    private int id;
    private String name;
    private int age;
    private String sex;
    public User() {
        super();
    }
    public User(int id, String name, int age, String sex) {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
        this.sex = sex;
    }
    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 int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + ", age=" + age + ", sex="
                + sex + "]";
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + age;
        result = prime * result + id;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        result = prime * result + ((sex == null) ? 0 : sex.hashCode());
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        User other = (User) obj;
        if (age != other.age)
            return false;
        if (id != other.id)
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        if (sex == null) {
            if (other.sex != null)
                return false;
        } else if (!sex.equals(other.sex))
            return false;
        return true;
    }
}

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"> 
<mapper namespace="com.mycom.mybatis_1.bean.userMapper"> 
    <!-- cache 开启二级缓存 -->
    <cache></cache>
    <!-- 根据id查询,得到一个user对象 -->
    <select id="getUser" parameterType="int" 
        resultType="com.mycom.mybatis_1.bean.User">
        select * from users where id=#{id}
    </select>
    <!-- CRUD 操作 -->
    <insert id="addUser" parameterType="com.mycom.mybatis_1.bean.User">
        insert into users(name,age) values (#{name},#{age})
    </insert>    
    <delete id="delUser" parameterType="int">
        delete from users where id=#{id}
    </delete>    
    <update id="updUser" parameterType="com.mycom.mybatis_1.bean.User">
        update users set name=#{name},age=#{age} where id=#{id}
    </update>
    <!-- 
    <select id="getAllUsers" resultType="com.mycom.mybatis_1.bean.User">
        select * from users
    </select>    
    <select id="getAllUsers" resultType="_User">
        select * from users
    </select>
     -->
    <select id="getAllUsers" resultType="User">
        select * from users
    </select>    
    <!-- 模糊查询,区间查询 -->
    <select id="getUser2" parameterType="ConditionUser" resultType="User">
        select * from users where name like #{name} and age between #{minAge} and #{maxAge}
    </select>    
    <select id="getUser3" parameterType="ConditionUser" resultType="User">
        select * from users where age between #{minAge} and #{maxAge}         
        <if test='name != "%null%"'>
         and name like #{name} 
        </if>        
    </select>    
    <select id="getUser4" parameterType="ConditionUser" resultType="User">
            select * from users where age>=#{minAge} and age<=#{maxAge}
        <if test='name!="%null%"'>and name like #{name}</if>
    </select>    
    <!-- 
        查询得到男性或女性的数量, 如果传入的是0就女性否则是男性
        CALL mybatis.get_user_count(1, @user_count);
     -->
    <select id="getUserCount" statementType="CALLABLE" parameterMap="getCountMap">
         call mybatis.get_user_count(?,?)
     </select>
     <parameterMap type="java.util.Map" id="getCountMap">
         <parameter property="sex_id" mode="IN" jdbcType="INTEGER"/>
         <parameter property="user_count" mode="OUT" jdbcType="INTEGER"/>
     </parameterMap>       
</mapper>

conf.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>
    <properties resource="db.properties" />    
    <!-- 配置实体类的别名 -->
    <typeAliases>
        <typeAlias type="com.mycom.mybatis_1.bean.User" alias="_User"/>
        <package name="com.mycom.mybatis_1.bean"/>
    </typeAliases>
    <environments default="development"><!-- development:开发模式; work:工作模式 -->
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <!-- 
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis" />
                <property name="username" value="root" />
                <property name="password" value="064417" />
                 -->
                <property name="driver" value="${driver}" />
                <property name="url" value="${url}" />
                <property name="username" value="${username}" />
                <property name="password" value="${password}" />
            </dataSource>
        </environment>
    </environments>    
    <mappers>
        <mapper resource="com/mycom/mybatis_1/bean/userMapper.xml"/>
        <mapper class="com.mycom.mybatis_1.bean.UserMapper1"/>
        
        <mapper resource="com/mycom/mybatis_1/bean/orderMapper.xml"/>
        <mapper resource="com/mycom/mybatis_1/bean/classMapper.xml"/>
        <mapper resource="com/mycom/mybatis_1/bean/teacherMapper.xml"/>
        <mapper resource="com/mycom/mybatis_1/bean/studentMapper.xml"/>
    </mappers>
</configuration>

Test1.java

package com.mycom.mybatis_1.select;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
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 com.mycom.mybatis_1.bean.User;
public class Test1 {    
    public static void main(String[] args) throws IOException {        
//        String resource = "conf.xml";
//        // 加载mybatis的配置文件(它也加载关联的映射文件)
//        Reader reader = Resources.getResourceAsReader(resource);
//        // 构建sqlSession的工厂
//        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder()
//                .build(reader);
//        // 创建能执行映射文件中sql的sqlSession
//        SqlSession session = sessionFactory.openSession();
//        // 映射sql的标识字符串
//        String statement = "com.mycom.mybatis_1.bean.userMapper"
//                + ".getUser";
//        // 执行查询返回一个唯一user对象的sql
//        User user = session.selectOne(statement, 1);
//        System.out.println(user);
        String resource = "conf.xml";
        InputStream is = Test1.class.getClassLoader().getResourceAsStream(resource);
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
        SqlSession session = factory.openSession();        
        String statement = "com.mycom.mybatis_1.bean.userMapper.getUser";
        User user = session.selectOne(statement, 2);
        session.close();
        System.out.println(user);
    }
}

动力节点在线课程涵盖零基础入门,高级进阶,在职提升三大主力内容,覆盖Java从入门到就业提升的全体系学习内容。全部Java视频教程免费观看,相关学习资料免费下载!对于火爆技术,每周一定时更新!如果想了解更多相关技术,可以到动力节点在线免费观看MyBatis框架视频教程学习哦!

0人推荐
共同学习,写下你的评论
0条评论
杨晶珍
程序员杨晶珍

98篇文章贡献357785字

相关课程 更多>

作者相关文章更多>

推荐相关文章更多>

Java面试题及答案整理

提枪策马乘胜追击04-21 20:01

Spring常见面试题

代码小兵92504-17 16:07

Java零基础实战项目——五子棋

代码小兵98804-25 13:57

Java string类详解

杨晶珍05-11 14:54

6道经典算法面试题

杨晶珍05-12 16:39

发评论

举报

0/150

取消