一.搭建环境,

建立数据库

 CREATE TABLE user(
id int(11) not NULL AUTO_INCREMENT,
userName varchar(50) DEFAULT NULL,
userAge int(11) DEFAULT NULL,
userAddress varchar(200) DEFAULT NULL,
PRIMARY KEY(id)
)ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

建立一个myBatis的java项目(不需要web项目)

然后倒入jar包

建总配置文件:

在src下建configration包.在建Configurations.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>
<typeAliases>
<typeAlias type="com.user.User" alias="User"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis"/>
<property name="username" value="root"/>
<property name="password" value="123"/>
</dataSource>
</environment>
</environments> <mappers>
<mapper resource="configration/User.xml"/>     </mappers>
</configuration>

建user的实体类和映射文件:

com.user.User代码:

 package com.user;

 public class User {
private int id;
private String userName;
private String userAge;
private String userAddress;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserAge() {
return userAge;
}
public void setUserAge(String userAge) {
this.userAge = userAge;
}
public String getUserAddress() {
return userAddress;
}
public void setUserAddress(String userAddress) {
this.userAddress = userAddress;
} }

configration包下见User.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="User">
<select id="selectUserById" parameterType="int" resultType="User">
select * from user where id=#{id}
</select>
<select id="selectUserList" parameterType="int" resultType="User">
select * from user
</select>
<insert id="insertUser" keyProperty="id" useGeneratedKeys="true" parameterType="user">
insert into user
(userName,userAge)
values
(#{userName},#{userName})
</insert>
</mapper>

建测试类

 package test;

 import java.io.Reader;
import java.util.List; 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.user.User; public class Test {
private static SqlSessionFactory sqlSessionFactory;
private static Reader reader; static {
try {
reader = Resources.getResourceAsReader("configration/Configurations.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
SqlSession session = sqlSessionFactory.openSession();
try {
//User user = (User) session.selectOne("User.selectUserById", 2);
List<User> list=session.selectList("User.selectUserList");
for(User user:list){
System.out.println("姓名:"+user.getUserName());
System.out.println("年龄"+user.getUserAge());
System.out.println("地址:"+user.getUserAddress());
System.out.println("-----------------------------------------------------------");
} } catch (Exception e) {
System.out.println("出现异常了.....");
e.printStackTrace();
} finally {
session.close();
}
}
}

当你查看到从数据库中读取的数据时,说明环境搭建完毕了

如何获取插入数据的主键值呢?

package test;

import java.io.Reader;
import java.util.List; 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.user.User; public class Run {
private static SqlSessionFactory sqlSessionFactory;
private static Reader reader; static {
try {
reader = Resources.getResourceAsReader("mybatis.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
SqlSession session = sqlSessionFactory.openSession();
try {
User u=new User();
u.setUserAge(255);
u.setUserName("思思博士");
int count=session.insert("User.insertUser",u);//count受影响的行数
session.commit();
System.out.println("插入数据的id值:>>>>>>>>"+u.getId());
} catch (Exception e) {
System.out.println("出现异常了.....");
e.printStackTrace();
} finally {
session.close();
}
}
}

上面的count是受影响的行数

u.getId()才是插入数据的主键的id值

二.用接口的方式实现编程.

建立IUserOperation.java

 package inter;

 import java.util.List;

 import com.user.User;

 public interface IUserOperation {
public User selectUserById(int id);
public List<User> selectUserList();
}

建立IUser.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="inter.IUserOperation">
<select id="selectUserById" parameterType="int" resultType="User">
select * from user where id=#{id}
</select>
<select id="selectUserList" resultType="User">
select * from user
</select>
</mapper>

注意这个地方的namspace就不可以随意取名字了.必须是实现接口的地址.

在总配置文件中mappers添加一条xml:<mapper resource="configration/IUser.xml"/>

添加测试类:

 package test;

 import inter.IUserOperation;

 import java.io.Reader;
import java.util.List; 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.user.User; /**
* 以接口的方式编程
* 如果以这种方式的话,那么对应的sql的xml配置文件中的namespace必须是实现接口的具体地址
*/
public class TestInterface {
private static SqlSessionFactory sqlSessionFactory;
private static Reader reader; static {
try {
reader = Resources.getResourceAsReader("configration/Configurations.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
SqlSession session = sqlSessionFactory.openSession();
try {
IUserOperation userOperation=session.getMapper(IUserOperation.class);
/*User user=userOperation.selectUserById(3);
System.out.println(user.getUserAddress());
System.out.println(user.getUserName());*/ List<User> list=userOperation.selectUserList();
for(User user:list){
System.out.println("姓名:"+user.getUserName());
System.out.println("年龄:"+user.getUserAge());
System.out.println("地址:"+user.getUserAddress());
System.out.println("--------------------------------");
} } catch (Exception e) {
System.out.println("出现异常了.....");
e.printStackTrace();
} finally {
session.close();
}
}
}

三,使用myBatis完成增删改查.

重新修改以下文件.

IUser.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="inter.IUserOperation">
<!-- 返回list数据集时使用的返回map -->
<resultMap type="User" id="resultListUserMap">
<id column="id" property="id" />
<result column="userName" property="userName"/>
<result column="userAge" property="userAge"/>
<result column="userAddress" property="userAddress"/>
</resultMap>
<select id="selectUserById" parameterType="int" resultType="User">
select * from user where id=#{id}
</select>
<select id="selectUsers" parameterType="String" resultMap="resultListUserMap">
select * from user where userName like #{userName}
</select>
<!--
执行增加操作的SQL语句.id和parameterType分别与IUserOperation接口中的
adUser方法的名字和参数类型一致.以#{name}的形式引用User参数的name属性.
myBatis将使用反射读取User参数的此属性.#{name}中name大小写敏感.
seGeneratedKeys设置为true,表明要myBatis获取自由数据库自动生成的主键;
keyProperty="id"指定把获取到的主键值注入到User的id属性
-->
<insert id="addUser" parameterType="User" useGeneratedKeys="true" keyProperty="id">
insert into user(userName,userAge,userAddress)
values(#{userName},#{userAge},#{userAddress});
</insert> <update id="updateUser" parameterType="User">
update user set userName=#{userName},userAge=#{userAge},userAddress=#{userAddress}
where id=#{id}
</update> <delete id="deleteUser" parameterType="int">
delete from user where id=#{id}
</delete> </mapper>

IUserOperation.java

 package inter;

 import java.util.List;

 import com.user.User;

 public interface IUserOperation {
public User selectUserById(int id);
public List<User> selectUsers(String userName);
public void addUser(User user);
public void updateUser(User user);
public void deleteUser(int id);
}

Test1.java

 package test;

 import inter.IUserOperation;

 import java.io.Reader;
import java.util.List; 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.user.User; public class Test1 {
private static SqlSessionFactory sqlSessionFactory;
private static Reader reader;
static {
try {
reader = Resources
.getResourceAsReader("configration/Configurations.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (Exception e) {
e.printStackTrace();
}
}
public void getUserList(String userName){
SqlSession session=sqlSessionFactory.openSession();
try {
IUserOperation userOperation=session.getMapper(IUserOperation.class);
List<User> users=userOperation.selectUsers(userName);
for(User user:users){
System.out.println("id:"+user.getId());
System.out.println("name:"+user.getUserName());
System.out.println("age:"+user.getUserAge());
System.out.println("address:"+user.getUserAddress());
System.out.println("-----------------");
}
} catch (Exception e) {
System.out.println("查询出错了......");
}finally{
session.close();
} } /**
* 添加数据,必须提交事务,否则不会写入dao数据库
* @param args
*/
public void addUser(){
User user=new User();
user.setUserAddress("安徽,舒城");
user.setUserAge(26);
user.setUserName("思思博士");
SqlSession session=sqlSessionFactory.openSession();
try {
IUserOperation userOperation=session.getMapper(IUserOperation.class);
userOperation.addUser(user);
session.commit();
System.out.println("当前增加的id为:"+user.getId());
} catch (Exception e) {
System.out.println("添加出现异常啦........");
}finally{
session.close();
}
} /**
*
* @param args
*/
public void updateUser(){
User user=new User();
user.setUserAddress("安徽,舒城,千人桥镇");
user.setUserAge(260);
user.setUserName("思思博士");
user.setId(4);
SqlSession session=sqlSessionFactory.openSession();
try {
IUserOperation userOperation=session.getMapper(IUserOperation.class);
userOperation.updateUser(user);
session.commit();
//System.out.println("当前增加的id为:"+user.getId());
} catch (Exception e) {
System.out.println("更新出现异常啦........");
}finally{
session.close();
}
} /**
* 删除数据
* @param args
*/
public void deleteUser(int id){
SqlSession session=sqlSessionFactory.openSession();
try {
IUserOperation userOperation=session.getMapper(IUserOperation.class);
userOperation.deleteUser(id);
session.commit();
System.out.println("数据删除成功");
} catch (Exception e) {
System.out.println("数据删除失败啦.....");
}
finally{
session.close();
}
} public static void main(String[] args) {
Test1 test1=new Test1();
//查询列表
test1.getUserList("%");
//test1.addUser();//添加数据
//test1.updateUser();//更新数据
//test1.deleteUser(3);//删除数据
}
}

四.联合查询:

IJoinUser.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="inter.IUserJoinOperation">
<resultMap type="User" id="resultListUserMapss">
<id column="id" property="id" />
<result column="userName" property="userName"/>
<result column="userAge" property="userAge"/>
<result column="userAddress" property="userAddress"/>
</resultMap>
<!-- User联合文章进行查询方法之一的配置(多对一的方式) -->
<resultMap type="News" id="resultUserNewsListMap">
<id property="id" column="Id" />
<result property="title" column="title" />
<result property="content" column="content" />
<association property="user" javaType="User">
<id property="id" column="id" />
<result property="userName" column="userName"/>
<result property="userAddress" column="userAddress"/>
</association>
</resultMap> <select id="getUserNewsList" parameterType="int" resultMap="resultUserNewsListMap">
select user.id,user.userName,user.userAge,user.userAddress,
news.id,news.userId,news.title,news.content
from user,news
where user.id=news.userId and user.id=#{id}
</select> </mapper>

IUserOperation.java

 package inter;

 import java.util.List;

 import com.user.News;

 public interface IUserJoinOperation {
public List<News> getUserNewsList(int userId);
}

测试类:

 package test;

 import inter.IUserJoinOperation;
import inter.IUserOperation; import java.io.Reader;
import java.util.List; 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.user.News;
import com.user.User; public class Test2 {
private static SqlSessionFactory sqlSessionFactory;
private static Reader reader;
static {
try {
reader = Resources
.getResourceAsReader("configration/Configurations.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 联合查询
* @param args
*/
public void getUserNews(int userId){
SqlSession session=sqlSessionFactory.openSession();
try {
IUserJoinOperation joinOperation=session.getMapper(IUserJoinOperation.class);
List<News> newsList=joinOperation.getUserNewsList(userId);
for(News news:newsList){
System.out.println("id:"+news.getId());
System.out.println("title:"+news.getTitle());
System.out.println("content:"+news.getContent());
System.out.println("userId:"+news.getUser().getId());
System.out.println("name:"+news.getUser().getUserName());
System.out.println("age:"+news.getUser().getUserAge());
System.out.println("address:"+news.getUser().getUserAddress());
System.out.println("------------------------------------");
}
System.out.println("输出完毕....");
} catch (Exception e) {
System.out.println("联合查询失败啦.......");
}
finally{
session.close();
}
} public static void main(String[] args) {
Test2 test2=new Test2();
//查询列表
test2.getUserNews(4);
}
}

其实还可以用另外一种方法:

修改IJoinUser.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="inter.IUserJoinOperation">
<resultMap type="User" id="resultListUserMapss">
<id column="id" property="id" />
<result column="userName" property="userName"/>
<result column="userAge" property="userAge"/>
<result column="userAddress" property="userAddress"/>
</resultMap>
<!-- User联合文章进行查询方法之一的配置(多对一的方式) -->
<resultMap type="News" id="resultUserNewsListMap">
<id property="id" column="Id" />
<result property="title" column="title" />
<result property="content" column="content" />
<association property="user" resultMap="resultListUserMapss" javaType="User" />
<!-- <association property="user" javaType="User">
<id property="id" column="id" />
<result property="userName" column="userName"/>
<result property="userAddress" column="userAddress"/>
</association> -->
</resultMap> <select id="getUserNewsList" parameterType="int" resultMap="resultUserNewsListMap">
select user.id,user.userName,user.userAge,user.userAddress,
news.id,news.userId,news.title,news.content
from user,news
where user.id=news.userId and user.id=#{id}
</select> </mapper>

这个地方我测试了一下,不知道为什么总是只能查出一条语句,但是sql语句直接在mysql中查询的话,可以查询多条的,哪位大神知道答案的,请告知啊.

本文非原创:

http://blog.csdn.net/techbirds_bao/article/details/9233599/

myBatis实例的更多相关文章

  1. MyBatis实例教程--开发环境搭建

    MyBatis实例教程--开发环境搭建 准备工作: 1.mybatis 的开发环境搭建,选择: eclipse j2ee 版本,mysql 5.1 ,jdk 1.7,mybatis3.2.0.jar包 ...

  2. Spring 整合Mybatis实例

    演示样例下载地址:http://download.csdn.net/detail/geloin/4506640 本文基于Spring 注解,让Spring跑起来.本文使用Mysql数据库. (1) 导 ...

  3. MyBatis实例教程--以接口的方式编程

    以接口的方式编程: 只需要修改两个地方即可, 1.mapper.xml(实体类)配置文件, 注意mapper的namespace的名字是mapper对象的完整路径名com.xiamen.mapper. ...

  4. Mybatis实例教程整体说明

    什么是mybatisMyBatis是支持普通SQL查询,存储过程和高级映射的优秀持久层框架.MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及结果集的检索.MyBatis使用简单的XML或 ...

  5. Mybatis实例增删改查(二)

    创建实体类: package com.test.mybatis.bean; public class Employee { private Integer id; private String las ...

  6. Mybatis实例及配置(一)

    创建实体类: package com.test.mybatis.bean; public class Employee { private Integer id; private String las ...

  7. Mybatis实现数据的增删改查(CRUD)

    什么是 MyBatis? MyBatis 是支持普通 SQL 查询,存储过程和高级映射的优秀持久层框架. MyBatis 消除了几乎所有的 JDBC 代码和参数的手工设置以及对结果集的检索.MyBat ...

  8. MyBatis学习--简单的增删改查

    jdbc程序 在学习MyBatis的时候先简单了解下JDBC编程的方式,我们以一个简单的查询为例,使用JDBC编程,如下: Public static void main(String[] args) ...

  9. 转!!!Mybatis实现数据的增删改查(CRUD)

    什么是 MyBatis? MyBatis 是支持普通 SQL 查询,存储过程和高级映射的优秀持久层框架. MyBatis 消除了几乎所有的 JDBC 代码和参数的手工设置以及对结果集的检索.MyBat ...

随机推荐

  1. JSP 相关试题(二)

    填空题 1.W3C是指___万维网联盟_______. 2.Internet采用的通信协议是___TCP/IP___. 3.当今比较流行的技术研发模式是__C/S__和__B/S__的体系结构来实现的 ...

  2. jQuery中怎么添加innerText、innerHtml(转)

    发现如果我在div或者其他非表单的标签中赋值,原本用普通的js就直接document.getElementById("id").innerHtml(或者其他几个)就可以了. 但是在 ...

  3. Linux启动过程详解 (转)

    启动第一步--加载BIOS当你打开计算机电源,计算机会首先加载BIOS信息,BIOS信息是如此的重要,以至于计算机必须在最开始就找到它.这是因为BIOS中包含了CPU的相关信息.设备启动顺序信息.硬盘 ...

  4. Android ActionBarSherlock使用教程

    Android ActionBarSherlock使用教程 本文转自 http://www.chenwg.com/android/actionbarsherlock%E4%BD%BF%E7%94%A8 ...

  5. 【spring】non-compatible bean definition of same name and class

    org.springframework.beans.factory.BeanDefinitionStoreException: Unexpected excep tion parsing XML do ...

  6. Linux中ftp不能上传文件/目录的解决办法

    在linux中不能上传文件或文件夹最多的问题就是权限问题,但有时也不一定是权限问题了,像我就是空间不够用了,下面我来总结一些ftp不能上传文件/目录的解决办法   在排除用户组和权限等问题后,最可能引 ...

  7. Func系列1:安装配置

    简介 Func是由红帽子公司以Fedora平台构建的统一网络控制器,是为解决集群管理.监控问题而设计开发的系统管理框架.它是一个能有效简化多服务多服务器系统管理工作的工具,它易于学习.使用和扩展,功能 ...

  8. Learning Puppet — Variables, Conditionals, and Facts

    Begin $my_variable = "A bunch of text" notify {$my_variable:} Yup, that’s a variable, all ...

  9. SVN:通过Client端打tag

    教你如何使用svnClient打tag~给公司人用的! 1.进入代码主目录 2.右击空白处“TortoiseSVN”—->“Branch/tag” 3.点地址栏右侧的 (选择tags存放目录) ...

  10. mac 下使用wireshark监听网络上的数据

    分三个步骤:    1.wireshark安装        wireshark运行需要mac上安装X11,mac 10.8的系统上默认是没有X11的.先去http://xquartz.macosfo ...