mybatis应用实例学习
MyBatis下载地址: http://code.google.com/p/mybatis/
搭建第一个mybatis应用
创建系统所需数据库
--
--数据库 tb_user
--
drop table if exists tb_user;
create table tb_user(
id int primary key auto_increment comment '主键',
username varchar(40) not null unique comment '用户名',
password varchar(40) not null comment '密码',
email varchar(40) comment '邮件',
age int comment '年龄',
sex char(2) not null comment '性别'
);
项目结构图:
实体类User
package com.icreate.entity;
/**
*
*
* @version : 1.0
*
* @author : 苏若年 <a href="mailto:DennisIT@163.com">发送邮件</a>
*
* @since : 1.0 创建时间: 2013-4-9 上午11:15:50
*
* @function: TODO
*
*/
public class User {
private int id;
private String username;
private String password;
private String sex;
private String email;
private int age;
//getter and setter
}
方案一: 基于配置文件
数据dao接口
package com.icreate.dao;
import java.util.List;
import com.icreate.entity.User;
/**
*
*
* @version : 1.0
*
* @author : 苏若年 <a href="mailto:DennisIT@163.com">发送邮件</a>
*
* @since : 1.0 创建时间: 2013-4-9 上午11:36:34
*
* @function: TODO
*
*/
public interface UserDao {
/**
* 新增用户
* @param user
* @return
*/
public int insert(User user);
/**
* 修改用户
* @param user
* @return
*/
public int update(User user);
/**
* 删除用户
* @param userName
* @return
*/
public int delete(String userName);
/**
* 查询所有用户
* @return
*/
public List<User> selectAll();
/**
* 查询数据库中总记录条数
* @return
*/
public int countAll();
/**
* 根据用户名查询用户
* @param userName
* @return
*/
public User findByUserName(String userName);
}
UserDaoMapper.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.icreate.dao.UserDao"> <select id="countAll" resultType="int"> <!-- 查询表中记录总数 --> select count(*) c from tb_user; </select> <select id="selectAll" resultType="com.icreate.entity.User"> <!-- 查询表中的所有用户 --> select * from tb_user order by username asc </select> <insert id="insert" parameterType="com.icreate.entity.User"> <!-- 向数据库中插入用户 --> insert into tb_user(username,password,email,sex,age) values(#{username},#{password},#{email},#{sex},#{age}) </insert> <update id="update" parameterType="com.icreate.entity.User"> <!-- 更新库中的用户 --> update tb_user set username=#{username},password=#{password},email=#{email},sex=#{sex},age=#{age} where username=#{username} </update> <delete id="delete" parameterType="String"> <!-- 删除用户 --> delete from tb_user where username=#{username} </delete> <select id="findByUserName" parameterType="String" resultType="com.icreate.entity.User"> <!-- 根据用户名查找用户 --> select * from tb_user where username=#{username} </select> </mapper>
需要注意的是,这里的id应该与UserDao中定义的方法名相同,sql语句结尾不能用分号
MyBatis-Configuration.xml文件
主测试类
package com.icreate.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 sun.security.krb5.internal.UDPClient;
import com.icreate.dao.UserDao;
import com.icreate.entity.User;
/**
*
*
* @version : 1.0
*
* @author : 苏若年 <a href="mailto:DennisIT@163.com">发送邮件</a>
*
* @since : 1.0 创建时间: 2013-4-9 上午11:58:03
*
* @function: TODO
*
*/
public class MybatisHandler {
public static void main(String[] args) throws Exception {
String resource = "MyBatis-Configuration.xml"; //mybatis配置文件的路径
Reader reader = Resources.getResourceAsReader(resource);
SqlSessionFactoryBuilder builfer = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builfer.build(reader);
SqlSession session = factory.openSession();
UserDao userDao = session.getMapper(UserDao.class);
//创建对象
User user = new User();
user.setUsername("苏若年");
user.setPassword("dennisit");
user.setEmail("dennisit@163.com");
user.setSex("男");
user.setAge(80);
//增加用户
//userDao.insert(user);
//查询数据库中记录总数
System.out.println("数据库中的记录数:" + userDao.countAll());
//根据用户名查找
User usn = userDao.findByUserName("苏若年");
if(null!=usn){
System.out.println("根据用户名查找的信息[" +usn.getId() + "," + usn.getUsername() + "," + usn.getEmail()+"]");
}
//更新用户
User updUser = new User();
updUser.setUsername("苏若年"); //更新用户是按照用户名查找,然后更新的.所以要修改的数据前后必须是同一个用户名
updUser.setEmail("update@163.com");
updUser.setPassword("update");
updUser.setAge(20);
userDao.update(updUser); //执行更新操作
//查询所有用户记录
List<User> list = userDao.selectAll();
for(int i=0;i<list.size();i++){
User us = list.get(i);
System.out.println("[" + us.getId() + "," + us.getUsername() + "," + us.getEmail()+"]");
}
userDao.delete("苏若年");
System.out.println("执行删除后数据库中的记录数:" + userDao.countAll());
session.commit();
}
}
程序运行结果
数据库中的记录数:1
根据用户名查找的信息[1,苏若年,dennisit@163.com]
[1,苏若年,update@163.com]
执行删除后数据库中的记录数:0
参考文档: http://www.cnblogs.com/wushiqi54719880/archive/2011/07/26/2117601.html
方案二:基于Annotation
数据表与实体类不变,项目结构图
UserDao中使用Annotation
package com.icreate.dao;
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import com.icreate.entity.User;
/**
*
*
* @version : 1.0
*
* @author : 苏若年 <a href="mailto:DennisIT@163.com">发送邮件</a>
*
* @since : 1.0 创建时间: 2013-4-9 上午11:36:34
*
* @function: TODO
*
*/
public interface UserDao {
@Insert("insert into tb_user(username,password,email,sex,age) values(#{username},#{password},#{email},#{sex},#{age})")
public int insert(User user);
@Update("update tb_user set username=#{username},password=#{password},email=#{email},sex=#{sex},age=#{age} where username=#{username}")
public int update(User user);
@Delete("delete from tb_user where username=#{username}")
public int delete(String userName);
@Select("select * from tb_user ")
public List<User> selectAll();
@Select("select count(*) from tb_user")
public int countAll();
@Select("select * from tb_user where username=#{username}")
public User findByUserName(String userName);
}
MyBatis-Configuration.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>
<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://localhost:3306/db_mybatis?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments>
</configuration>
DBHelper辅助类
package com.icreate.util;
import java.io.IOException;
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.icreate.dao.UserDao;
/**
*
*
* @version : 1.0
*
* @author : 苏若年 <a href="mailto:DennisIT@163.com">发送邮件</a>
*
* @since : 1.0 创建时间: 2013-4-9 下午02:36:43
*
* @function: 单例设计模式
*
*/
public class DBHelper {
private static DBHelper dbHelper = new DBHelper();
private SqlSessionFactory sqlSessionFactory = null;
private DBHelper(){
try {
String resource = "MyBatis-Configuration.xml"; //mybatis配置文件的路径
Reader reader = Resources.getResourceAsReader(resource);
SqlSessionFactoryBuilder builfer = new SqlSessionFactoryBuilder();
sqlSessionFactory = builfer.build(reader);
sqlSessionFactory.getConfiguration().addMapper(UserDao.class);
} catch (IOException e) {
e.printStackTrace();
}
}
public static DBHelper getInstance(){
return dbHelper;
}
public SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
数据操作模拟类
package com.icreate.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 sun.security.krb5.internal.UDPClient;
import com.icreate.dao.UserDao;
import com.icreate.entity.User;
import com.icreate.util.DBHelper;
/**
*
*
* @version : 1.0
*
* @author : 苏若年 <a href="mailto:DennisIT@163.com">发送邮件</a>
*
* @since : 1.0 创建时间: 2013-4-9 上午11:58:03
*
* @function: TODO
*
*/
public class MybatisHandler {
public static void main(String[] args) throws Exception {
SqlSession session = DBHelper.getInstance().getSqlSession();
UserDao userDao = session.getMapper(UserDao.class);
//创建对象
User user = new User();
user.setUsername("苏若年");
user.setPassword("dennisit");
user.setEmail("dennisit@163.com");
user.setSex("男");
user.setAge(80);
//增加用户
userDao.insert(user);
//查询数据库中记录总数
System.out.println("数据库中的记录数:" + userDao.countAll());
//根据用户名查找
User usn = userDao.findByUserName("苏若年");
if(null!=usn){
System.out.println("根据用户名查找的信息[" +usn.getId() + "," + usn.getUsername() + "," + usn.getEmail()+"]");
}
//更新用户
User updUser = new User();
updUser.setUsername("苏若年"); //更新用户是按照用户名查找,然后更新的.所以要修改的数据前后必须是同一个用户名
updUser.setEmail("update@163.com");
updUser.setPassword("update");
updUser.setAge(20);
updUser.setSex("男");
userDao.update(updUser); //执行更新操作
//查询所有用户记录
List<User> list = userDao.selectAll();
for(int i=0;i<list.size();i++){
User us = list.get(i);
System.out.println("[" + us.getId() + "," + us.getUsername() + "," + us.getEmail()+"]");
}
userDao.delete("苏若年");
System.out.println("执行删除后数据库中的记录数:" + userDao.countAll());
session.commit();
}
}
程序运行结果
数据库中的记录数:1
根据用户名查找的信息[2,苏若年,dennisit@163.com]
[2,苏若年,update@163.com]
执行删除后数据库中的记录数:0
参考文档: http://www.cnblogs.com/wushiqi54719880/archive/2011/07/26/2117614.html
在此感谢博友红枫落叶,笔者新接触mybatis,学习时得到落叶文章很大的帮助!
转载请注明出处:[http://www.cnblogs.com/dennisit/archive/2013/04/09/3010801.html]
热爱生活,热爱Coding,敢于挑战,用于探索 ...