1.需要导入的jar包
2.项目目录
3.log4j.properties:配置日志输出
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
log4j.rootLogger=error, stdout
log4j.logger.com.springframework=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
3.sqlMapConfig.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="per.czt.mybatics.domain.User" alias="User"/>
</typeAliases>
<mappers>
<!-- 映射User.xml -->
<mapper resource="per/czt/mybatics/domain/User.xml"/>
</mappers>
</configuration>
4.beans.xml:Spring容器的配置文件,在Spring中配置Mybatis
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<!-- 数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/mybaticsdb?useSSL=false&serverTimezone=UTC&characterEncoding=utf-8"></property>
<property name="username" value="root"></property>
<property name="password" value="123456"></property>
</bean>
<!-- 配置sessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation" value="classpath:sqlMapConfig.xml"></property>
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 事务相关控制 -->
<bean name="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 通知 -->
<tx:advice id="userTxAdvice"
transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="insert*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="find*" read-only="true" />
<tx:method name="get*" read-only="true" />
<tx:method name="select*" read-only="true" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="pc" expression="execution(* per.czt.mybatics.service.*.*(..))" />
<!--把事务控制在Service层-->
<aop:advisor pointcut-ref="pc" advice-ref="userTxAdvice" />
</aop:config>
<bean id="userDao" class="per.czt.mybatics.dao.UserDaoImpl">
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
<bean id="userService" class="per.czt.mybatics.service.UserServiceImpl">
<property name="userDao" ref="userDao"></property>
</bean>
</beans>
5.User类和User.xml文件:将domain对象与数据库中的表相关联
User.java
package per.czt.mybatics.domain;
public class User {
private Integer id;
private String name;
private Integer age;
private String address;
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 getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
User.xml:可以自己配置sql语句的生成方式
<?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="per.czt.mybatics.domain.User">
<!--<mapper namespace="sysmanager"> -->
<sql id="cols">id,name,age,address </sql>
<!-- 查询所有记录 -->
<select id="listAll" resultType="User">
select * from user
</select>
<!-- 统一的查询方法 -->
<select id="find" parameterType="User" resultType="User">
select * from user where 1=1
<if test="id!=null">
and id=#{id}
</if>
<if test="name!=null">
and name like "%"#{name}"%"
</if>
<if test="age!=null">
and age=#{age}
</if>
<if test="address!=null">
and address=#{address}
</if>
</select>
<!-- 统一的修改方法 -->
<update id="update" parameterType="User">
update user
<set>
<if test="name!=null">
name=#{name},
</if>
<if test="age!=null">
age=#{age},
</if>
<if test="address!=null">
address=#{address}
</if>
</set>
where id=#{id}
</update>
<insert id="insert" parameterType="per.czt.mybatics.domain.User">
insert into user(name,age,address) values(#{name},#{age},#{address})
</insert>
<delete id="delete" parameterType="Integer" >
delete from user where id=#{id}
</delete>
<select id="get" parameterType="User" resultType="per.czt.mybatics.domain.User">
select <include refid="cols"/> from user where id=#{id}
</select>
<select id="getLikeName" parameterType="String" resultType="per.czt.mybatics.domain.User">
select * from user where name like CONCAT(CONCAT('%', #{name}), '%');
</select>
<!--
<select id="select" parameterType="int" resultType="User">
select * from user
</select>
<insert id="create" parameterType="User">
insert into user(id,name) values(#{id},#{name})
</insert>
<update id="update" parameterType="User">
update user set id=(#{id}),name=(#{name})
</update>
<delete id="delete" parameterType="User">
delete from user where id=(#{id});
</delete> -->
</mapper>
6.dao层:与数据库的关联,实现对数据库的增删改查
UserDao.java(接口)
package per.czt.mybatics.dao;
import java.util.List;
import per.czt.mybatics.domain.User;
public interface UserDao {
public List<User> listAll();
public User getById(Integer id);
public int insert(User u);
public int update(User u);
public int delete(Integer id);
}
UserDaoImpl.java(实现类)
package per.czt.mybatics.dao;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import per.czt.mybatics.domain.User;
public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao {
@Override
public int insert(User u) {
SqlSession sqlSession=this.getSqlSession();
int flag= sqlSession.insert("per.czt.mybatics.domain.User.insert", u);
sqlSession.commit();
return flag;
}
@Override
public int update(User u) {
return this.getSqlSession().update("per.czt.mybatics.domain.User.update", u);
}
@Override
public int delete(Integer id) {
return this.getSqlSession().delete("per.czt.mybatics.domain.User.delete", id);
}
@Override
public List<User> listAll() {
return this.getSqlSession().selectList("per.czt.mybatics.domain.User.find");
}
@Override
public User getById(Integer id) {
// TODO Auto-generated method stub
return (User)this.getSqlSession().selectOne("per.czt.mybatics.domain.User.select", id);
}
}
7.service层:调用dao层,处理dao层的结果
UserService.java(接口)
package per.czt.mybatics.service;
import java.util.List;
import per.czt.mybatics.domain.User;
public interface UserService {
public List<User> listAll();
public User getById(Integer id);
public int insert(User u);
public int update(User u);
public int delete(Integer id);
}
UserServiceImpl.java(实现类)
package per.czt.mybatics.service;
import java.util.List;
import per.czt.mybatics.dao.UserDao;
import per.czt.mybatics.domain.User;
public class UserServiceImpl implements UserService {
private UserDao userDao;
public UserDao getUserDao() {
return userDao;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Override
public List<User> listAll() {
return userDao.listAll();
}
@Override
public User getById(Integer id) {
// TODO Auto-generated method stub
return userDao.getById(id);
}
@Override
public int insert(User u) {
// TODO Auto-generated method stub
return userDao.insert(u);
}
@Override
public int update(User u) {
// TODO Auto-generated method stub
return userDao.update(u);
}
@Override
public int delete(Integer id) {
// TODO Auto-generated method stub
return userDao.delete(id);
}
}
8.测试类
TestMybaticsspring.java
package per.czt.mybatics.test;
import java.util.List;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import per.czt.mybatics.domain.User;
import per.czt.mybatics.service.UserService;
public class TestMybaticsspring {
private static UserService userService;
static
{
ApplicationContext ac=new ClassPathXmlApplicationContext("beans.xml");
userService=(UserService) ac.getBean("userService");
}
@Test
public static void insert()
{
User u=new User();
u.setName("afs");
u.setAddress("sgsdg");
u.setAge(13);
int flag=userService.insert(u);
if(flag==1)
{
System.out.println("插入成功!");
}
else
{
System.out.println("插入失败");
}
}
@Test
public static void update()
{
User u=new User();
u.setName("2244");
u.setAddress("2424");
u.setAge(1313);
u.setId(14);
int flag=userService.update(u);
if(flag==1)
{
System.out.println("更新成功!");
}
else
{
System.out.println("更新失败");
}
}
@Test
public static void delete()
{
int flag=userService.delete(14);
if(flag==1)
{
System.out.println("删除成功!");
}
else
{
System.out.println("删除失败");
}
}
public static void listAll()
{
List<User> userList=userService.listAll();
for(User u:userList)
{
System.out.println("id:"+u.getId()+" "+"name:"+u.getName()+" "+"age:"+u.getAge()+" "+"address:"+u.getAddress());
}
}
public static void main(String[] args) {
//insert();
//update();
//delete();
listAll();
}
}