myBatis实例
一.搭建环境,
建立数据库
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实例的更多相关文章
- MyBatis实例教程--开发环境搭建
MyBatis实例教程--开发环境搭建 准备工作: 1.mybatis 的开发环境搭建,选择: eclipse j2ee 版本,mysql 5.1 ,jdk 1.7,mybatis3.2.0.jar包 ...
- Spring 整合Mybatis实例
演示样例下载地址:http://download.csdn.net/detail/geloin/4506640 本文基于Spring 注解,让Spring跑起来.本文使用Mysql数据库. (1) 导 ...
- MyBatis实例教程--以接口的方式编程
以接口的方式编程: 只需要修改两个地方即可, 1.mapper.xml(实体类)配置文件, 注意mapper的namespace的名字是mapper对象的完整路径名com.xiamen.mapper. ...
- Mybatis实例教程整体说明
什么是mybatisMyBatis是支持普通SQL查询,存储过程和高级映射的优秀持久层框架.MyBatis消除了几乎所有的JDBC代码和参数的手工设置以及结果集的检索.MyBatis使用简单的XML或 ...
- Mybatis实例增删改查(二)
创建实体类: package com.test.mybatis.bean; public class Employee { private Integer id; private String las ...
- Mybatis实例及配置(一)
创建实体类: package com.test.mybatis.bean; public class Employee { private Integer id; private String las ...
- Mybatis实现数据的增删改查(CRUD)
什么是 MyBatis? MyBatis 是支持普通 SQL 查询,存储过程和高级映射的优秀持久层框架. MyBatis 消除了几乎所有的 JDBC 代码和参数的手工设置以及对结果集的检索.MyBat ...
- MyBatis学习--简单的增删改查
jdbc程序 在学习MyBatis的时候先简单了解下JDBC编程的方式,我们以一个简单的查询为例,使用JDBC编程,如下: Public static void main(String[] args) ...
- 转!!!Mybatis实现数据的增删改查(CRUD)
什么是 MyBatis? MyBatis 是支持普通 SQL 查询,存储过程和高级映射的优秀持久层框架. MyBatis 消除了几乎所有的 JDBC 代码和参数的手工设置以及对结果集的检索.MyBat ...
随机推荐
- linux概念之/etc
[Thu Apr 02 15:04:32 1028 /dev/pts/0 192.168.2.250 /etc]#ll |grep -v "^d"|wc -l99[Thu Apr ...
- wikioi 1205 单词倒排
/*====================================================================== 1205 单词翻转 题目描述 Description ...
- 【转】越狱的 iPhone、iPad 通过网站实现一键安装 ipa 格式的 APP 应用
1.已经越狱的 iPhone.iPad 设备,当通过其自带的 safari 浏览器访问 ipa 应用下载网站时,利用 itms-services 协议,可以一键安装 ipa 文件的 iOS 应用,例如 ...
- js键盘事件全面控制
js键盘事件全面控制 主要分四个部分第一部分:浏览器的按键事件第二部分:兼容浏览器第三部分:代码实现和优化第四部分:总结 第一部分:浏览器的按键事件 用js实现键盘记录,要关注浏览器的三种按键事件类型 ...
- Html下拉框的定义以及JS、Jquary取值、添加和移除
现在有一id=test的下拉框,怎么拿到选中的那个值呢? 分别使用javascript原生的方法和jquery方法 <select id="test" name=" ...
- 服务器能访问共享,但是ping不通解决方案
今天发现客户反映后台连不上数据库,远程程查看之后发现机器可以访问服务器共享,但是ping网络的时候ping不通.Ip设置也没问题,网络也都连上了,而且客户反映他们那其它机器都能连上. 百度了一下,发现 ...
- 运行Appium碰到的坑们
运行Appium的时候,碰到的那些坑 1. java命令会出现error:could not open ...jvm.cfg 出现这种情况大多是因为电脑上之前安装过JDK,卸载重装之后,运行java命 ...
- jquery事件切换hover/toggle
1.hover([over,]out) 一个模仿悬停事件(鼠标移动到一个对象上面及移出这个对象)的方法.这是一个自定义的方法,它为频繁使用的任务提供了一种“保持在其中”的状态. 当鼠标移动到一个匹配的 ...
- Zabbix 教程
Zabbix 教程http://blog.csdn.net/linuxlsq/article/details/52606086 MySQL在以下几种情况会创建临时表:1.UNION查询:2.用到TEM ...
- 概要设计、详细设计(三)关键点(Know-How)、运用技巧
1. 关键点(Know-How).运用技巧 4.1 设计准则 制定设计准则是概要设计阶段的最主要.最关键的工作.在实际工作中往往忽略,多数项目牺牲在这个环节.制定设计准则着眼于如何更好的做设计, ...