标签:tac sts 不用 names builder utf8 manager schema 位置
本文通过加载mybatis-configuration.xml 文件来产生SqlSessionFactory,然后通过SqlSessionFactory去产生sqlSession,然后在通过 sqlSession对数据库表所映射的实体类进行增删改查操作。通过spring的DI和IOC,能产生对象并管理对象的声明周期,而sprig的AOP也能管理对象的事务。主要有两点:
1、需要spring通过单例的方式管理 SqlSessionFactory,并用 SqlSessionFactory 去创建 sqlSession
2、持久层的 mapper 需要spring 管理
本文源码脚本的下载地址是: http://ovy7j2mnc.bkt.clouddn.com/mybatisSpringPro.rar
DROP database IF EXISTS `myDb2`;
create database myDb2;
use myDb2;DROP TABLE IF EXISTS `User`;
CREATE TABLE `User` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
使用Maven创建JAVA工程,名称为 mybatisSpringPro。
pom.xml的参考内容为:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.bank</groupId>
<artifactId>mybatisSpringPro</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>mybatisSpringPro</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>3.2.18.RELEASE</spring.version>
</properties>
<dependencies>
<!--mysql数据库驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<!--log4j日志包 -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.6.1</version>
</dependency>
<!-- mybatis ORM框架 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.1</version>
</dependency>
<!-- JUnit单元测试工具 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
</dependency>
<!--mybatis-spring适配器 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<!--Spring框架核心库 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- aspectJ AOP 织入器 -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.9</version>
</dependency>
<!--Spring java数据库访问包,在本例中主要用于提供数据源 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>
</dependencies>
</project>
log4j.properties
log4j.rootLogger=DEBUG, 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
新建 User.java
package com.mybatis.pojo;
/**
*
* user表所对应的实体类
*
* */
public class User
{
//实体类的属性和表的字段名称一一对应
private int id;
private String username ;
private int age;
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 int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
@Override
public String toString()
{
return "User [id=" + id + ", username=" + username + ", age=" + age + "]";
}
}
持久层选用MyBatis,先编写一个配置文件,然后用自动化工具生成dao层以下的所有代码,配置文件generatorConfig.xml供生成器用,详细的内容请看我前面的几篇博客
generatorConfig.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!--数据库驱动-->
<classPathEntry location="mysql-connector-java-5.1.6.jar"/>
<context id="DB2Tables" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressDate" value="true"/>
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!--数据库链接地址账号密码-->
<jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1:3306/myDb2" userId="root" password="123456">
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!--生成Model类存放位置-->
<javaModelGenerator targetPackage="com.bank.model" targetProject="src">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!--生成映射文件存放位置-->
<sqlMapGenerator targetPackage="com.bank.mapping" targetProject="src">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!--生成Dao类存放位置-->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.bank.dao" targetProject="src">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!--生成对应表及类名-->
<table tableName="person" domainObjectName="Person" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
</context>
</generatorConfiguration>
上面的路径请酌情修改,保存之后在cmd下面 进入生成器的jar包所在的文件夹,然后执行以下命令:
java -jar mybatis-generator-core-1.3.5.jar -configfile generatorConfig.xml -overwrite
<?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>
<mappers>
<mapper resource="com/mybatis/mapper/UserMapper.xml"/>
</mappers>
</configuration>
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<!-- 加载Spring配置文件 -->
<context:property-placeholder location="classpath*:db.properties" />
<!-- 配置数据源-->
<bean id="jdbcDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName">
<value>${jdbc.driver}</value>
</property>
<property name="url">
<value>${jdbc.url}</value>
</property>
<property name="username">
<value>${jdbc.username}</value>
</property>
<property name="password">
<value>${jdbc.password}</value>
</property>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="jdbcDataSource" />
<property name="configLocation" value="classpath:mybatis.cfg.xml"></property>
</bean>
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.mybatis.mapper.UserMapper"></property>
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
</beans>
注意: 在定义SqlSessionFactoryBean的时候,dataSource属性是必须指定的,它表示用于连接数据库的数据源。当然,我们也可以指定一些其他的属性,下面简单列举几个:
db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/myDb?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=123456
<?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.mybatis.mapper.UserMapper">
<select id="getUser" parameterType="com.mybatis.pojo.User" resultType="com.mybatis.pojo.User">
SELECT * FROM user WHERE username=#{username} AND age=#{age}
</select>
<insert id="addUser" parameterType="com.mybatis.pojo.User" >
INSERT INTO user (id,username,age) VALUES (#{id},#{username},#{age})
</insert>
<update id="updateUser" parameterType="com.mybatis.pojo.User">
UPDATE user SET username=#{username} WHERE id=#{id}
</update>
<delete id="deleteUser" parameterType="int">
DELETE FROM user WHERE id=#{id}
</delete>
</mapper>
新建UserMapper.java
package com.mybatis.mapper;
import com.mybatis.pojo.User;
/**
*
*/
public interface UserMapper
{
public User getUser(User user);
public void addUser(User user);
public void updateUser(User user);
public void deleteUser(int UserId);
}
package mybatisSpringPro;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.mybatis.mapper.UserMapper;
import com.mybatis.pojo.User;
public class UserMapperTest
{
ApplicationContext ctx = null;
@Before
public void setUp() throws Exception {
ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
}
@Test
public void testAdd() throws Exception {
try{
UserMapper userMapper=(UserMapper) ctx.getBean("userMapper");
System.out.println( "userMapper=" + userMapper);
User user=new User();
user.setUsername("zhaoliu");
user.setAge(21);
userMapper.addUser(user);
User user2=new User();
user2.setUsername("wangwu");
user2.setAge(22);
userMapper.addUser(user2);
System.out.println("添加成功");
}catch(Exception e){
e.printStackTrace();
}
}
@Test
public void testSel() {
try{
UserMapper userMapper=(UserMapper) ctx.getBean("userMapper");
System.out.println( "userMapper=" + userMapper);
User user=new User();
user.setUsername("zhaoliu");
user.setAge(21);
User oneUser = userMapper.getUser(user);
System.out.println("* oneUser=" + oneUser);
}catch(Exception e){
e.printStackTrace();
}
}
@Test
public void testUpdate(){
//修改数据
User user=new User();
user.setUsername("aaa");
user.setId( 3);
try{
UserMapper userMapper=(UserMapper) ctx.getBean("userMapper");
userMapper.updateUser(user);
System.out.println("修改成功");
}catch(Exception e){
e.printStackTrace();
}
}
@Test
public void testDel(){
try{
UserMapper userMapper=(UserMapper) ctx.getBean("userMapper");
userMapper.deleteUser(9);
System.out.println("删除成功");
}catch(Exception e){
e.printStackTrace();
}
}
}
资料参考:
http://qiuqiu0034.iteye.com/blog/1172298
MyBatis 学习总结 05 Mybatis3.x与Spring3.x整合 OLD
标签:tac sts 不用 names builder utf8 manager schema 位置
原文地址:http://www.cnblogs.com/wangshuo1/p/7554598.html