查看原文:http://www.ibloger.net/article/293.html
之前一直实用Hibernate进行开发,最近公司在使用Mybatis,根据网上的示例,做了一个简单的Demo,以便日后复习
总体结构如下图
首先是创建一个工程,然后导入两个jar包,然后编写mybatis的jdbc配置文件Configuration.xml
Configuration.xml
User类,文章中省略getter和setter方法
package com.demo.bean;
import java.util.Date;
public class User {
private String id;
private String name;
private String password;
private Date birthday;
private String address;
}
然后是创建sql映射文件User.xml
update valid_user set name=#{name},address=#{address} where id=#{id}
insert into valid_user(id,name,password,address) values(seq_valid_user.nextval,#{name},#{password},#{address})
delete from valid_user where id=#{id}
然后就是编辑测试类
package com.demo.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.demo.bean.User;
public class TestConnection {
private static SqlSessionFactory sqlSessionFactory;
private static Reader reader;
static {
try {
reader = Resources.getResourceAsReader("Configuration.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 查询所有User对象
* @param id
*/
public static void selectAllUsers() {
SqlSession session = sqlSessionFactory.openSession();
try {
List listUsers = session.selectList("com.demo.bean.User.selectAllUsers");
for (User user:listUsers) {
System.out.println("ID:" + user.getId() + ",姓名:" + user.getName() + ",密码:" + user.getPassword() + ",住址:" + user.getAddress());
}
} finally {
session.close();
}
}
/**
* 根据id查询User对象
* @param id
*/
public static void findUserById(String id) {
SqlSession session = sqlSessionFactory.openSession();
try {
User user = (User) session.selectOne("com.demo.bean.User.findUserById", id);
System.out.println("ID:" + user.getId() + ",姓名:" + user.getName() + ",密码:" + user.getPassword() + ",住址:" + user.getAddress());
} finally {
session.close();
}
}
/**
* 根据id更新User对象
* @param id
*/
public static void updateUserById(String id,User user) {
SqlSession session = sqlSessionFactory.openSession();
try {
session.update("com.demo.bean.User.updateUserById",user);
session.commit();
} finally {
session.close();
}
}
/**
* 添加一条User对象
*/
public static void addUser(User user) {
SqlSession session = sqlSessionFactory.openSession();
try {
session.insert("com.demo.bean.User.addUser",user);
session.commit();
} finally {
session.close();
}
}
/**
* 删除一条User对象
*/
public static void deleteUserById(String id) {
SqlSession session = sqlSessionFactory.openSession();
try {
session.delete("com.demo.bean.User.deleteUserById",id);
session.commit();
} finally {
session.close();
}
}
public static void main(String[] args) {
selectAllUsers();
// findUserById("1"); // 根据id查询User对象
// User user=new User();
// user.setId("2");
// user.setName("Zams");
// user.setAddress("河南、郑州");
// updateUserById("2",user); // 根据id更新User对象
// User add_user=new User();
// add_user.setName("古力娜扎");
// add_user.setPassword("3412312");
// add_user.setAddress("河南、郑州、开封");
// addUser(add_user); // 根据id更新User对象
// deleteUserById("4");
}
}
ID:1,姓名:X-rapido,密码:rapido,住址:北京朝阳、海淀
ID:2,姓名:Zams,密码:gril,住址:河南、郑州
ID:3,姓名:盖尔加朵,密码:3412312,住址:河南、郑州
ID:5,姓名:古力娜扎,密码:3412312,住址:河南、郑州、开封
其他内容:
总体结构内容不变,主要修改java注解配置类(Service类)、配置文件、测试类3个地方即可
UserMapper类
package com.demo.bean;
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;
/**
* 使用注解映射,不需要写实现类,但要在Mybatis配置文件中将此类进行注册
*/
public interface UserMapper {
@Select("select * from valid_user")
List selectAllUsers();
@Select("select * from valid_user where id=#{id}")
User findUserById(String id);
@Update("update valid_user set name=#{name},address=#{address} where id=#{id}")
int updateUserById(User user);
@Insert("insert into valid_user(id,name,password,address) values(seq_valid_user.nextval,#{name},#{password},#{address})")
int addUser(User user);
@Delete("delete from valid_user where id=#{id}")
int deleteUserById(String id);
}
Mybatis配置文件中 configuration.xml修改 mapper内容
将测试类中的如查询所有代码的com.demo.bean.User.selectAllUsers修改为com.demo.bean.UserMapper.selectAllUsers即可。
测试效果同xml的配置效果一样。
在实际应用中,有时候需要对Mybatis进行多参数传值,这时候可以使用Map对象进行查询
比如在登录时,传入账户名和密码,在xml在将 parameterType设置为map参数类型, parameterType="map"
Map map = new HashMap();
map.put("name", userName);
map.put("password", password);
return sqlSession.selectOne("com.demo.bean.User.loginUser", map);
log4j的配置文件可以是xml形式,也可以是.properties文件形式
log4j.properties(方式一)
log4j.rootLogger=DEBUG, Console
#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
log4j.logger.java.sql.ResultSet=INFO
log4j.logger.org.apache=INFO
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
log4j.xml