一、首先创建数据库
二、创建项目工程
先导入文件
编写配置文件
db.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/db
username=root
password=root
config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "mybatis-3-config.dtd" >
<configuration>
<properties resource="db.properties"></properties>
<!-- 开启复杂的自动映射 -->
<!-- <settings>
<setting name="autoMappingBehavior" value="FULL"/>
</settings> -->
<typeAliases>
<package name="cn.lexed.pojo"/>
</typeAliases>
<environments default="dev">
<environment id="dev">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="cn.lexed.dao"/>
</mappers>
</configuration>
log4j.properties
log4j.rootLogger=DEBUG,CONSOLE,file
#log4j.rootLogger=ERROR,ROLLING_FILE
log4j.logger.cn.lexed.dao=debug
log4j.logger.com.ibatis=debug
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=debug
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=debug
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=debug
log4j.logger.java.sql.Connection=debug
log4j.logger.java.sql.Statement=debug
log4j.logger.java.sql.PreparedStatement=debug
log4j.logger.java.sql.ResultSet=debug
log4j.logger.org.tuckey.web.filters.urlrewrite.UrlRewriteFilter=debug
######################################################################################
# Console Appender \u65e5\u5fd7\u5728\u63a7\u5236\u8f93\u51fa\u914d\u7f6e
######################################################################################
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.Threshold=error
log4j.appender.CONSOLE.Target=System.out
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern= [%p] %d %c - %m%n
######################################################################################
# DailyRolling File \u6bcf\u5929\u4ea7\u751f\u4e00\u4e2a\u65e5\u5fd7\u6587\u4ef6\uff0c\u6587\u4ef6\u540d\u683c\u5f0f:log2009-09-11
######################################################################################
log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.DatePattern=yyyy-MM-dd
log4j.appender.file.File=log.log
log4j.appender.file.Append=true
log4j.appender.file.Threshold=error
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-M-d HH:mm:ss}%x[%5p](%F:%L) %m%n
log4j.logger.com.opensymphony.xwork2=error
导入工具包
MybatisUtils.java
package cn.lexed.utils;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MybatisUtils {
private static SqlSessionFactory factory;
static{ //在静态代码块里,factory只会被创建一次
try{
InputStream is=Resources.getResourceAsStream("config.xml");
factory=new SqlSessionFactoryBuilder().build(is);
}catch(Exception e){
e.printStackTrace();
}
}
//获取SqlSession
public static SqlSession createSqlSession(){
return factory.openSession(true); //true为自动提交
}
public static void closeSqlSession(SqlSession sqlSession){
if(null!=sqlSession){
sqlSession.close();
}
}
}
创建People类
People.java
package cn.lexed.pojo;
public class People {
private Integer id;
private String name;
private Integer age;
private String addres;
public People() {
super();
}
public People(Integer id, String name, Integer age, String addres) {
super();
this.id = id;
this.name = name;
this.age = age;
this.addres = addres;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getAddres() {
return addres;
}
public void setAddres(String addres) {
this.addres = addres;
}
@Override
public String toString() {
return "People [id=" + id + ", name=" + name + ", age=" + age + ", addres=" + addres + "]";
}
}
编写动态增、删、改、查方法
PeopleMapper.java
package cn.lexed.dao;
import cn.lexed.pojo.People;
public interface PeopleMapper {
public People getPeopleById(People people);//查询
public void updatePeople(People people);//修改
public void insertPeople(People people);//添加
public void deletePeople(People people);//删除
}
PeopleMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "mybatis-3-mapper.dtd" >
<mapper namespace="cn.lexed.dao.PeopleMapper">
<!-- 查询 -->
<select id="getPeopleById" parameterType="people" resultType="people">
select * from people
<where>
<if test="name!=null and name!=''">
name=#{name}
</if>
<if test="addres!=null and addres!=''">
and addres=#{addres}
</if>
</where>
</select>
<!-- 修改 -->
<update id="updatePeople" parameterType="people">
update people
<set>
<if test="name!=null and name!=''">
name=#{name},
</if>
<if test="age!=null and age!=''">
age=#{age},
</if>
<if test="addres!=null and addres!=''">
addres=#{addres}
</if>
</set>
<where>
<if test="id!=null">
id=#{id}
</if>
</where>
</update>
<!-- 添加 -->
<sql id="key">
<trim suffixOverrides=",">
<if test="name!=null and name!=''">name,</if>
<if test="age!=null and age!=''">age,</if>
<if test="addres!=null and addres!=''">addres,</if>
</trim>
</sql>
<sql id="value">
<trim suffixOverrides=",">
<if test="name!=null and name!=''">#{name},</if>
<if test="age!=null and age!=''">#{age},</if>
<if test="addres!=null and addres!=''">#{addres},</if>
</trim>
</sql>
<insert id="insertPeople" parameterType="people">
insert into people(<include refid="key"/>) values(<include refid="value"/>)
</insert>
<!-- 删除 -->
<delete id="deletePeople" parameterType="people">
delete from people
<where>
<if test="id!=null">
id=#{id}
</if>
</where>
</delete>
</mapper>
编写测试类
Test(Jun)
package cn.lexed.test;
import static org.junit.Assert.*;
import org.apache.ibatis.session.SqlSession;
import cn.lexed.dao.PeopleMapper;
import cn.lexed.pojo.People;
import cn.lexed.utils.MybatisUtils;
public class Test {
@org.junit.Test
public void test(){
//1.获取SqlSession对象
SqlSession s=MybatisUtils.createSqlSession();
People people=new People();
people.setName("马云");
people.setAddres("杭州");
People peo=s.getMapper(PeopleMapper.class).getPeopleById(people);
System.out.println(peo);
}
@org.junit.Test
public void test1(){
//1.获取SqlSession对象
SqlSession s=MybatisUtils.createSqlSession();
People people=new People();
people.setName("马云");
people.setAge(18);
people.setAddres("深圳");
people.setId(5);
s.getMapper(PeopleMapper.class).updatePeople(people);
}
@org.junit.Test
public void test2(){
//1.获取SqlSession对象
SqlSession s=MybatisUtils.createSqlSession();
People people=new People();
people.setName("李嘉诚");
people.setAge(95);
people.setAddres("香港");
s.getMapper(PeopleMapper.class).insertPeople(people);
}
@org.junit.Test
public void test3(){
//1.获取SqlSession对象
SqlSession s=MybatisUtils.createSqlSession();
People people=new People();
people.setId(29);
s.getMapper(PeopleMapper.class).deletePeople(people);
}
}