目录
5.6. 思考CURD的dao中的问题 9········典型的小星星·的···
6.2. 通过sqlSession.getMapper(Class) 9
7.2.1. mapUnderscoreToCamelCase用法: 13
7.3.2. typeAliases的使用2---使用扫描包 14
10.2. choose,when,otherwise 27
11.1.2. 使用session.clearCache()强制查询不缓存。 30
11.1.3. 执行update,delete,insert 语句的时候,会刷新缓存 30
WHERE o.order_number = ‘20140921001‘ 33
WHERE o.order_number = ‘20140921001‘ 35
1、书写mybatis的入门案例
2、书写dao层的curd的操作
3、详细去学习mybatis中的配置信息
3.1 mybatis-config.xml 全局配置
3.2 *mapper.xml 局部的配置
直接点击 Finsh完成
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>cn.itcast.mybatis</groupId>
<artifactId>mybatis-test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>cn.itcast.parent</groupId>
<artifactId>itcast-parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- Mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
</dependency>
</dependencies>
</project>
导入后效果
mybatis
public static void main(String[] args) throws Exception {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
// 加载驱动
Class.forName("com.mysql.jdbc.Driver");
// 创建数据库连接
String url = "jdbc:mysql://127.0.0.1:3306/mybatis";
String user = "root";
String password = "123456";
connection = DriverManager.getConnection(url, user, password);
// 获取statement对象
String sql = "SELECT * FROM tb_user WHERE id = ?";
preparedStatement = connection.prepareStatement(sql);
// 设置参数,有2个参数,第一个是下标,从1开始,第二个是参数值
preparedStatement.setLong(1, 1L);
// 执行查询
resultSet = preparedStatement.executeQuery();
// 遍历结果集
while (resultSet.next()) {
System.out.println("id = " + resultSet.getLong("id"));
System.out.println("name = " + resultSet.getString("name"));
System.out.println("passwd = " + resultSet.getString("password"));
}
} finally {
// 关闭连接释放资源
if (null != resultSet) {
resultSet.close();
}
if (null != preparedStatement) {
preparedStatement.close();
}
if (null != connection) {
connection.close();
}
}
}
1、加载驱动问题:
每次执行都加载驱动
驱动名称,硬编码到java代码中,如果需要修改驱动。需要修改java文件
解决方案:将驱动名称放入到外部的配置文件
2、数据库的连接信息,硬编码到java代码中,解决方案:外部配置文件
3、设置参数的问题:
参数下标硬编码了。需要人为的去判断参数的位置。
4、遍历结果集:需要人工的判断字段名,以及个位置参数类型,不方便
是否可以:能够将结果集直接映射到一个pojo对象中
5、频繁的创建连接,关闭连接。导致资源浪费,影响性能,解决:连接池。
在mybatis的包里面可以看到,ibatis的字样。 Call xxx(1,ss)
hello,看demo(官方文档)
向工程的pom文件中,添加mybatis的依赖
在工程的根目录下面创建一个mybatis-config.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/mybatis"/>
<property name="username" value="root"/>
<property name="password" value="admin"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper.xml"/>
</mappers>
</configuration>
<?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="abc">
<select id="selectUser" resultType="cn.itcast.mybatis.pojo.User">
select * from tb_user where id = #{id}
</select>
</mapper>
1、创建一个局部的mapper.xml
2、在全局的mybatis-config.xml 中去添加mapper.xml的配置
3、书写java代码,调用指定的statement,并且传递参数信息。获取返回值
问题原因:
mybatis没有引入 mapper
需要在mybatis-config.xml 中使用mapper 去引入外部的mapper.xml
log4j.rootLogger=DEBUG,A1
log4j.logger.org.mybatis=DEBUG
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%c]-[%p] %m%n
日志信息
2016-01-08 10:56:02,081 [main] [org.apache.ibatis.logging.LogFactory]-[DEBUG] Logging initialized using ‘class org.apache.ibatis.logging.slf4j.Slf4jImpl‘ adapter.
2016-01-08 10:56:02,093 [main] [org.apache.ibatis.datasource.pooled.PooledDataSource]-[DEBUG] PooledDataSource forcefully closed/removed all connections.
2016-01-08 10:56:02,093 [main] [org.apache.ibatis.datasource.pooled.PooledDataSource]-[DEBUG] PooledDataSource forcefully closed/removed all connections.
2016-01-08 10:56:02,094 [main] [org.apache.ibatis.datasource.pooled.PooledDataSource]-[DEBUG] PooledDataSource forcefully closed/removed all connections.
2016-01-08 10:56:02,094 [main] [org.apache.ibatis.datasource.pooled.PooledDataSource]-[DEBUG] PooledDataSource forcefully closed/removed all connections.
org.apache.ibatis.session.defaults.DefaultSqlSessionFactory@62ccf439
org.apache.ibatis.session.defaults.DefaultSqlSession@40378309
2016-01-08 10:56:02,148 [main] [org.apache.ibatis.transaction.jdbc.JdbcTransaction]-[DEBUG] Opening JDBC Connection
2016-01-08 10:56:02,309 [main] [org.apache.ibatis.datasource.pooled.PooledDataSource]-[DEBUG] Created connection 495124555.
2016-01-08 10:56:02,309 [main] [org.apache.ibatis.transaction.jdbc.JdbcTransaction]-[DEBUG] Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@1d83004b]
2016-01-08 10:56:02,321 [main] [abc.selectUser]-[DEBUG] ==> Preparing: select * from tb_user where id = ?
2016-01-08 10:56:02,351 [main] [abc.selectUser]-[DEBUG] ==> Parameters: 1(Long)
2016-01-08 10:56:02,377 [main] [abc.selectUser]-[DEBUG] <== Total: 1
User [id=1, userName=null, password=123456, name=张三, age=30, sex=1, birthday=Wed Aug 08 00:00:00 CST 1984, created=Fri Sep 19 16:56:04 CST 2014, updated=Sun Sep 21 11:24:59 CST 2014]
2016-01-08 10:56:02,380 [main] [org.apache.ibatis.transaction.jdbc.JdbcTransaction]-[DEBUG] Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@1d83004b]
2016-01-08 10:56:02,381 [main] [org.apache.ibatis.transaction.jdbc.JdbcTransaction]-[DEBUG] Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@1d83004b]
2016-01-08 10:56:02,381 [main] [org.apache.ibatis.datasource.pooled.PooledDataSource]-[DEBUG] Returned connection 495124555 to pool.
0) 配置mybatis-config.xml 全局的配置文件
public Integer selectCount();
/**
* 根据id查询用户信息
* @param id
* @return
*/
public User queryUserById(Long id);
/**
* 查询所有用户
* @return
*/
public List<User> queryAllUser();
/**
* 添加用户信息
* @param user
*/
public void addUser(User user);
/**
* 修改用户信息
* @param user
*/
public void updateUser(User user);
/**
* 根据id删除用户信息
* @param id
*/
public void deleteUserById(Long id);
<?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">
<!-- namesapce 名称空间,一个标识 -->
<mapper namespace="user">
<select id="queryUserById" resultType="cn.itcast.mybatis.pojo.User">
select * from tb_user
where id = #{id}
</select>
<!-- resultType:指定结果集的映射的java对象类型 tb_user 对应到User这个类,所以配置 cn.itcast.mybatis.pojo.User -->
<select id="queryAllUser" resultType="cn.itcast.mybatis.pojo.User">
select * from tb_user
</select>
<!-- parameterType:定义传入参数类型 -->
<insert id="addUser" parameterType="cn.itcast.mybatis.pojo.User">
INSERT INTO tb_user (
id,
user_name,
password,
name,
age,
sex,
birthday,
created,
updated
) VALUES
( NULL,
#{userName},
#{password},
#{name},
#{age},
#{sex},
#{birthday},
NOW(),
NOW()
);
</insert>
<update id="updateUser" parameterType="cn.itcast.mybatis.pojo.User">
UPDATE tb_user SET
user_name = #{userName},
password = #{password},
name = #{name},
age = #{age},
sex = #{sex},
birthday = #{birthday},
updated = NOW() WHERE
(id = #{id});
</update>
<delete id="deleteUserById" parameterType="java.lang.Long">
delete from tb_user where id = #{id}
</delete>
</mapper>
// private UserDao userDao;
private UserMapper userMapper;
private SqlSession sqlSession;
@Before
public void setUp() throws Exception {
//全局配置文件路径
String resource = "mybatis-config.xml";
// 获取输入流
InputStream is = Resources.getResourceAsStream(resource);
// 构建sqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
sqlSession = sqlSessionFactory.openSession();
// 把userDao进行初始化
// userDao = new UserDaoImpl(sqlSession);
// 要求:
// 1、对应的mapper中的namesapce 必须和接口的全路径要一致
// 2、要求方法的名字和 statement的id的值一直
userMapper = sqlSession.getMapper(UserMapper.class);
}
@Test
public void testLogin(){
User user = userMapper.login("lisi", "123456");
System.out.println(user);
}
@Test
public void testQueryUserById() {
User user = userMapper.queryUserById(2l);
System.out.println(user);
}
@Test
public void testQueryAllUser() {
List<User> userlist = userMapper.queryAllUser();
for(User user :userlist){
System.out.println(user);
}
}
@Test
public void testAddUser() {
User user = new User();
user.setName("赵柳");
user.setAge(19);
user.setBirthday(new Date());
user.setPassword("123456");
user.setSex(1);
user.setuserName("zhaoliu1");
int num = userMapper.addUser(user);
// 有时候业务可能需要插入到数据库对应的id
System.out.println( "修改的数目"+num);
// 需要事务进行提交
System.out.println(user.getId());
sqlSession.commit();
}
@Test
public void testUpdateUser() {
// 更新操作
// 1、先去查询
User user = userMapper.queryUserById(1l);
user.setAge(100);
userMapper.updateUser(user);
// 提交事务
sqlSession.commit();
}
@Test
public void testDeleteUserById() {
userMapper.deleteUserById(9l);
sqlSession.commit();
}
@Test
public void testselectCount(){
System.out.println(userMapper.selectCount());
}
@Test
public void selectUserFromTable(){
this.userMapper.selectUserFromTable("tb_user");
}
查询数据的时候,查不到userName的信息,原因:数据库的字段名是user_name
POJO中的属性名字是userName
两端不一致,造成mybatis无法填充对应的字段信息。修改方法:在sql语句中使用别名
解决方案1:在sql语句中使用别名
解决方案2: 参考后面的resultMap –mapper具体的配置的时候
解决方案3:参考驼峰匹配 --- mybatis-config.xml 的时候
1、准备一个mybatis-config.xml 全局的配置信息
连接数据库的参数
引入mapper.xml
2、构建sqlSessionFactory。
3、获取sqlSession
4、通过sqlsession.insert update delete ,select ()完成数据库的crud的操作
方法中的参数 sqlSession.insert("名称名字.sql_id");
5、准备一个mapper.xml 书写各个sql语句
分别书写在<insert > <select > <update> <delete>
1、接口->实现类->mapper.xml
2、实现类中,使用mybatis的方式非常类似
3、sql statement 硬编码到java代码中。
思考:能否只写接口,不书写实现类,只编写Mapper.xml即可
因为在dao(mapper)的实现类中对sqlsession的使用方式很类似。mybatis提供了接口的动态代理
mapper.xml的 namespace 属性
如果希望使用mybatis通过的动态代理的接口,就需要namespace 中的值,和需要对应的Mapper(dao)接口的全路径一致
通过resource引入外部属性:
jdbc.properties
在URL后面添加 红色字体部分
url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8
设置参数 | 描述 | 有效值 | 默认值 |
cacheEnabled | 该配置影响的所有映射器中配置的缓存的全局开关。 | true | false | true |
lazyLoadingEnabled | 延迟加载的全局开关。当开启时,所有关联对象都会延迟加载。特定关联关系中可通过设置fetchType属性来覆盖该项的开关状态。 | true | false | false |
aggressiveLazyLoading | 当启用时,带有延迟加载属性的对象的加载与否完全取决于对任意延迟属性的调用;反之,每种属性将会按需加载。 | true | false | true |
multipleResultSetsEnabled | 是否允许单一语句返回多结果集(需要兼容驱动)。 | true | false | true |
useColumnLabel | 使用列标签代替列名。不同的驱动在这方面会有不同的表现,具体可参考相关驱动文档或通过测试这两种不同的模式来观察所用驱动的结果。 | true | false | true |
useGeneratedKeys | 允许 JDBC 支持自动生成主键,需要驱动兼容。如果设置为 true 则这个设置强制使用自动生成主键,尽管一些驱动不能兼容但仍可正常工作(比如 Derby)。 | true | false | False |
autoMappingBehavior | 指定 MyBatis 是否以及如何自动映射指定的列到字段或属性。NONE 表示取消自动映射;PARTIAL 只会自动映射没有定义嵌套结果集映射的结果集。FULL 会自动映射任意复杂的结果集(包括嵌套和其他情况)。 | NONE, PARTIAL, FULL | PARTIAL |
defaultExecutorType | 配置默认的执行器。SIMPLE 就是普通的执行器;REUSE 执行器会重用预处理语句(prepared statements);BATCH 执行器将重用语句并执行批量更新。 | SIMPLE REUSE BATCH | SIMPLE |
defaultStatementTimeout | 设置超时时间,它决定驱动等待数据库响应的秒数。 | Any positive integer | Not Set (null) |
safeRowBoundsEnabled | 允许在嵌套语句中使用行分界(RowBounds)。 | true | false | False |
mapUnderscoreToCamelCase | 是否开启自动驼峰命名规则(camel case)映射,即从经典数据库列名 A_COLUMN 到经典 Java 属性名 aColumn 的类似映射。 | true | false | False |
localCacheScope | MyBatis 利用本地缓存机制(Local Cache)防止循环引用(circular references)和加速重复嵌套查询。默认值为 SESSION,这种情况下会缓存一个会话中执行的所有查询。若设置值为 STATEMENT,本地会话仅用在语句执行上,对相同 SqlSession 的不同调用将不会共享数据。 | SESSION | STATEMENT | SESSION |
jdbcTypeForNull | 当没有为参数提供特定的 JDBC 类型时,为空值指定 JDBC 类型。某些驱动需要指定列的 JDBC 类型,多数情况直接用一般类型即可,比如 NULL、VARCHAR 或 OTHER。 | JdbcType enumeration. Most common are: NULL, VARCHAR and OTHER | OTHER |
lazyLoadTriggerMethods | 指定哪个对象的方法触发一次延迟加载。 | A method name list separated by commas | equals,clone,hashCode,toString |
defaultScriptingLanguage | 指定动态 SQL 生成的默认语言。 | A type alias or fully qualified class name. | org.apache.ibatis.scripting.xmltags.XMLDynamicLanguageDriver |
callSettersOnNulls | 指定当结果集中值为 null 的时候是否调用映射对象的 setter(map 对象时为 put)方法,这对于有 Map.keySet() 依赖或 null 值初始化的时候是有用的。注意原始类型(int、boolean等)是不能设置成 null 的。 | true | false | false |
logPrefix | 指定 MyBatis 增加到日志名称的前缀。 | Any String | Not set |
logImpl | 指定 MyBatis 所用日志的具体实现,未指定时将自动查找。 | SLF4J | LOG4J | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING | Not set |
proxyFactory | 为 Mybatis 用来创建具有延迟加载能力的对象设置代理工具。 | CGLIB | JAVASSIST | CGLIB |
帮助我们完成数据库的经典命名规则,到java的命名规则的映射
数据库的经典命名规则:userName === user_name 值的映射
已经为普通的 Java 类型内建了许多相应的类型别名。它们都是大小写不敏感的,需要注意的是由于重载原始类型的名称所做的特殊处理。
别名 | 映射的类型 |
_byte | byte |
_long | long |
_short | short |
_int | int |
_integer | int |
_double | double |
_float | float |
_boolean | boolean |
string | String |
byte | Byte |
long | Long |
short | Short |
int | Integer |
integer | Integer |
double | Double |
float | Float |
boolean | Boolean |
date | Date |
decimal | BigDecimal |
bigdecimal | BigDecimal |
object | Object |
map | Map |
hashmap | HashMap |
list | List |
arraylist | ArrayList |
collection | Collection |
iterator | Iterator |
类型处理器 | Java 类型 | JDBC 类型 |
BooleanTypeHandler | java.lang.Boolean, boolean | 任何兼容的布尔值 |
ByteTypeHandler | java.lang.Byte, byte | 任何兼容的数字或字节类型 |
ShortTypeHandler | java.lang.Short, short | 任何兼容的数字或短整型 |
IntegerTypeHandler | java.lang.,Integer int | 任何兼容的数字和整型 |
LongTypeHandler | java.lang.Long, long | 任何兼容的数字或长整型 |
FloatTypeHandler | java.lang.Float, float | 任何兼容的数字或单精度浮点型 |
DoubleTypeHandler | java.lang.Double, double | 任何兼容的数字或双精度浮点型 |
BigDecimalTypeHandler | java.math.BigDecimal | 任何兼容的数字或十进制小数类型 |
StringTypeHandler | java.lang.String | CHAR 和 VARCHAR 类型 |
ClobTypeHandler | java.lang.String | CLOB 和 LONGVARCHAR 类型 |
NStringTypeHandler | java.lang.String | NVARCHAR 和 NCHAR 类型 |
NClobTypeHandler | java.lang.String | NCLOB 类型 |
ByteArrayTypeHandler | byte[] | 任何兼容的字节流类型 |
BlobTypeHandler | byte[] | BLOB 和 LONGVARBINARY 类型 |
DateTypeHandler | java.util.Date | TIMESTAMP 类型 |
DateOnlyTypeHandler | java.util.Date | DATE 类型 |
TimeOnlyTypeHandler | java.util.Date | TIME 类型 |
SqlTimestampTypeHandler | java.sql.Timestamp | TIMESTAMP 类型 |
SqlDateTypeHandler | java.sql.Date | DATE 类型 |
SqlTimeTypeHandler | java.sql.Time | TIME 类型 |
ObjectTypeHandler | Any | 其他或未指定类型 |
EnumTypeHandler | Enumeration Type | VARCHAR-任何兼容的字符串类型,作为代码存储(而不是索引) |
EnumOrdinalTypeHandler | Enumeration Type | 任何兼容的 NUMERIC 或 DOUBLE 类型,作为位置存储(而不是代码本身)。 |
作用:将mapper.xml 文件配置到mybatis的环境中。
这里所谓的mapper接口路径。实际上就是dao的接口路径。在mybatis中,通常把dao的包叫做mapper
3、在mybatis-config.xml 中通过class路径,引入mapper。要求mapper.xml 中的名称空间是类的接口的全路径
1、mapper.xml 和 java文件没有分离。 明天和spring整合之后解决。
1、properties,引入外部的文件,保存了 jdbc相关参数
5、配置mapper,引入外部的mapper.xml ---使用扫描包的方式
id属性:当前名称空间下的statement的唯一标识。必须。要求id和mapper接口中的方法的名字一致。
resultType:将结果集映射为java的对象类型。必须(和 resultMap 二选一)
id属性:当前名称空间下的statement的唯一标识(必须属性);
id属性:当前名称空间下的statement的唯一标识(必须属性);
id属性:当前名称空间下的statement的唯一标识(必须属性);
查询表中的信息,有时候从历史表中去查询数据,有时候需要去新的表去查询数据。
注意#{} 只是替换? 这个功能,sql语句中 ? 只能出现where中。 当作一个变量
如果使用${} 去取出参数信息,则需要在方法的参数列表上加上一个注释@param 表示参数的名字
如果${} 没有指定参数名(在方法的参数列表中没有加入@Param)可以使用${value} 表示传递过来的参数。
user_name = #{userName} and password = #{password}
对于传入多个参数的时候,#{} 需要使用参数名的方式去获取数据。
在mapper.xml中使用 0,1这样的序号去,0表示第一个参数,1表示第二个参数。
dao层给servcie去使用。一个方法可能被多个service所使用。
使用#的方式,需要每个servcie方法都在传递参数之前,进行字符串拼接
在一个mapper.xml 中使用<sql> 去定义sql片段,然后在需要的位置使用<include> 引入
将所有的公用的SQL片段集中定义到一个Mapper.xml文件中,其他Mapper.xml文件如需引入,通过命名空间.id即可。
需求1:查询男性用户,如果输入了姓名,就使用姓名进行模糊查找,否则返回所有男性。
choose,when,otherwise 相当于java中的 if, elseif的逻辑
查询男性用户,如果输入了姓名则按照姓名模糊查找,姓名不为空时忽略年龄这个条件,当姓名为空,年龄不为空,则按照年龄查找。
<!-- queryUserManByNameOrAge 查询男性用户,如果输入了姓名则按照姓名模糊查找,
姓名不为空时忽略年龄这个条件,当姓名为空,年龄不为空,则按照年龄查找 -->
<select id="queryUserManByNameOrAge" resultType="User">
select * from tb_user where sex=1
<when test="name != null and name != ‘‘"> and user_name like ‘%${name}%‘ </when>
<if test="age > 0">and age = #{age}</if>
作用:完成WHERE和SET关键字,并且处理SQL语句的中语法错误。
练习:查询所有用户,如果输入了姓名按照姓名进行模糊查询,如果输入年龄,按照年龄进行查询。
10.3.4 set set标签可以替代sql语句里面的set,并且可以自动判断条件后的逗号分割
按照多个id查询用户信息 select * from tb_user where id in (1,2,3,4)
mybatis 的二级缓存的作用域是一个mapper的namespace ,同一个namespace中查询sql可以从缓存中命中。
在全局的mybatis-config.xml 中去关闭二级缓存
LEFT JOIN tb_user u ON u.id = o.user_id
WHERE o.order_number = ‘20140921001‘
核心思想:面向对象的思想,在Order对象中添加User对象。
使用resultType不能完成自动映射,所以需要手动完成结果集的映射,需要使用resultMap实现。
一对多查询:根据订单号查询订单,查询出下单人信息并且查询出订单明细。
LEFT JOIN tb_user u ON u.id = o.user_id
LEFT JOIN tb_orderdetail d ON d.order_id = o.id
WHERE o.order_number = ‘20140921001‘
多对多查询:查询订单,查询出下单人信息并且查询出订单详情中的商品数据。
<artifactId>cglib</artifactId>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<groupId>com.github.jsqlparser</groupId>
<artifactId>jsqlparser</artifactId>
<!-- com.github.pagehelper为PageHelper类所在包名 -->
<plugin interceptor="com.github.pagehelper.PageHelper">
<property name="dialect" value="mysql"/>
<!-- 设置为true时,使用RowBounds分页会进行count查询 会去查询出总数 -->
<property name="rowBoundsWithCount" value="true"/>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
1、创建spring的配置文件applicationContext.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
配置资源文件替换器
<!-- 使用spring自带的占位符替换功能 -->
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<!-- 配置资源文件 -->
<property name="locations">
<list>
<value>classpath:c3p0.properties</value>
</list>
</property>
</bean>
配置连接池:
<!-- 配置连接池 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="${c3p0.driverClass}"></property>
<property name="jdbcUrl" value="${c3p0.url}"></property>
<property name="user" value="${c3p0.user}"></property>
<property name="password" value="${c3p0.password}"></property>
</bean>
<!-- 配置SqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!--引入mybatis的总配置 -->
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
</bean>
<!-- 配置mapper -->
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="cn.itcast.mybatis.mapper.UserMapper" />
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
<!-- 配置mybatis mapper接口扫描器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="cn.itcast.mybatis.mapper" />
</bean>
多个包使用逗号分割即可:
<!-- 配置SqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!--引入mybatis的总配置 -->
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
<!-- 类型别名扫描包 -->
<property name="typeAliasesPackage" value="cn.itcast.mybatis.pojo"></property>
</bean>
<!-- 配置mapper.xml的文件夹,使java代码和xml文件分离 -->
<property name="mapperLocations" value="classpath:mapper/*.xml"></property>
servcie方法:
<context:component-scan base-package="cn.itcast.mybatis.service.impl"/>
测试:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- 定义事务管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 定义事务策略 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!--所有以query开头的方法都是只读的 -->
<tx:method name="query*" read-only="true" />
<!--其他方法使用默认事务策略 -->
<tx:method name="*" />
</tx:attributes>
</tx:advice>
<aop:config>
<!--pointcut元素定义一个切入点,execution中的第一个星号 用以匹配方法的返回类型,
这里星号表明匹配所有返回类型。 com.abc.dao.*.*(..)表明匹配cn.itcast.mybatis.service包下的所有类的所有
方法 -->
<aop:pointcut id="myPointcut" expression="execution(* cn.itcast.mybatis.service.*.*(..))" />
<!--将定义好的事务处理策略应用到上述的切入点 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="myPointcut" />
</aop:config>
</beans>
package cn.itcast.test;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.itcast.mybatis.pojo.User;
import cn.itcast.mybatis.service.UserService;
public class UserServiceTest {
UserService userService;
@Before
public void setUp() throws Exception {
String resource = "applicationContext.xml";
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(resource);
userService = applicationContext.getBean(UserService.class);
}
@Test
public void testGetUserById(){
User user = userService.getUserById(25L);
System.out.println(user);
}
}
原文:http://www.cnblogs.com/beyondcj/p/6271165.html