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&lt;=#{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);
}
}

db.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis
username=root
password=******

MyBatis 查询的更多相关文章

  1. mybatis 查询 xml list参数

    mybatis 查询 xml list参数: <select id="getByIds" resultType="string" parameterTyp ...

  2. MyBatis 查询映射自定义枚举

    背景                  MyBatis查询若想映射枚举类型,则需要从 EnumTypeHandler 或者 EnumOrdinalTypeHandler 中选一个来使用         ...

  3. mybatis查询异常-Error querying database. Cause: java.lang.ClassCastException: org.apache.ibatis.executor.ExecutionPlaceholder cannot be cast to java.util.List

    背景,mybatis查询的时候直接取的sqlsession,没有包装成SqlSessionTemplate,没有走spring提供的代理. 然后我写的获取sqlsession的代码没有考虑到并发的情况 ...

  4. mybatis查询语句的背后

    转载请注明出处... 一.前言 在先了解mybatis查询之前,先大致了解下以下代码的为查询做了哪些铺垫,在这里我们要事先了解,myabtis会默认使用DefaultSqlSessionFactory ...

  5. mybatis查询语句的背后之参数解析

    转载请注明出处... 一.前言 通过前面我们也知道,通过getMapper方式来进行查询,最后会通过mapperMehod类,对接口中传来的参数也会在这个类里面进行一个解析,随后就传到对应位置,与sq ...

  6. mybatis查询语句的背后之封装数据

    转载请注明出处... 一.前言 继上一篇mybatis查询语句的背后,这一篇主要围绕着mybatis查询的后期操作,即跟数据库交互的时候.由于本人也是一边学习源码一边记录,内容难免有错误或不足之处,还 ...

  7. mybatis查询结果和接收的不一样

    记一次大坑:mybatis查询结果和接收的不一样,折腾我好几个小时. 先上代码:代码是要查询排名,sql执行的结果 SELECT b.operator_id, b.class_count, b.cla ...

  8. 【mybatis】【mysql】mybatis查询mysql,group by分组查询报错:Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column

    mybatis查询mysql,group by分组查询报错:Expression #1 of SELECT list is not in GROUP BY clause and contains no ...

  9. 使用MyBatis查询 返回类型为int,但是当查询结果为空NULL,报异常的解决方法

    使用MyBatis查询 返回类型为int,但是当查询结果为空NULL,会报异常. 例如: <select id="getPersonRecordId" parameterTy ...

  10. mybatis查询日期时间数据得到long类型数据的问题

    使用mybatis查询数据时,如果数据库存储的是timestamp.datetime.date.time等时间类型,而Java bean也使用的是date类型,mybatis会自动将date类型转换为 ...

随机推荐

  1. 阿里巴巴Json工具-Fastjson讲解

    Fastjson是阿里巴巴公司开源的速度最快的Json和对象转换工具,一个Java语言编写的JSON处理器. 1.遵循http://json.org标准,为其官方网站收录的参考实现之一.2.功能qia ...

  2. Azure IOT (EventHub + Stream Analytics + Table Storage)的使用

    最近研究利用Azure的 Event hub ,Stream Analytics和TableStorage来实现IOT的一个方案, 利用Event hub来采集传感器设备数据值,然后输入到Stream ...

  3. UWP深入学习四:动画及图像

    Storyboarded animations Key-frame animations and easing function animations 缓动函数 缓动函数支持你将自定义数学公式应用到动 ...

  4. php 获取代码执行时间和消耗的内存

    做一些php性能测试的时候,要获取代码执行时间和消耗的内存,查了一下资料,发现php有自带的函数可以实现这个功能,具体实现代码如下: $t1 = microtime(true);// ... 执行代码 ...

  5. JS延时提示框

    p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 31.0px Consolas; color: #2b7ec3 } p.p2 { margin: 0.0px ...

  6. ubuntu wireshark 没有接口

    There are no interfaces on which a capture can be done 解决方法: Open a terminal by pressing Ctrl+Alt+T  ...

  7. DataTableToJson

    public static string CreateJsonParameters(DataTable dt,string JsonName) { StringBuilder JsonString = ...

  8. Django学习(二)

    一  高亮显示 <script type="text/javascript"> $(document).ready(function () { $("#nav ...

  9. java知识点--重写与重载

    重载(Overload): (1)方法重载是让类以统一的方式处理不同类型数据的一种手段.多个同名函数同时存在,具有不同的参数个数/类型.重载Overloading是一个类中多态性的一种表现.      ...

  10. Dynamic CRM 2013学习笔记(七)追踪、监控及性能优化

    本文将介绍CRM的三个内容追踪.监控及性能优化.追踪是CRM里一个很有用的功能,它能为我们的CRM调试或解决错误.警告提供有价值的信息:我们可以用window的性能监控工具来了解CRM的性能状况:最后 ...