Maven下載
https://wws.lanzous.com/icFBQhgbukj
Spring
<bean id="userdao" class="com.sdut.dao.UserDaoImpl" scope="prototype"/>
prototype 創(chuàng)建的對(duì)象不是同一個(gè)
singleton 創(chuàng)建的對(duì)象是同一個(gè)
Bean的依賴注入概念
依賴注入:它是Spring框架核心IOC的具體實(shí)現(xiàn)
在編寫(xiě)程序時(shí),通過(guò)控制翻轉(zhuǎn),把對(duì)象的創(chuàng)建交給Spring桶错,但是代碼中不可能出現(xiàn)沒(méi)有依賴的IOC解耦只是降低他們的依賴關(guān)系烈掠,但不會(huì)消除疗涉。例如:業(yè)務(wù)層仍然會(huì)調(diào)用持久層的方法亚侠,那這種業(yè)務(wù)層和持久層的依賴關(guān)系什往,在使用Spring之后软能,就讓Spring來(lái)維護(hù)了迎捺。簡(jiǎn)單的說(shuō),就是坐等框架把持久層對(duì)象傳入業(yè)務(wù)層查排,而不用我們?nèi)ト ?/p>
service 中需要dao 凳枝,因此將dao注入到service
set方法注入
//UserDao.java
package com.sdut.dao;
public interface UserDao {
void save();
}
//UserDaoImpl.java
package com.sdut.dao;
public class UserDaoImpl implements UserDao{
@Override
public void save() {
System.out.println("Hello, Spring !");
}
}
//ServiceDemo.java
package com.sdut.service;
public interface ServiceDemo {
void save();
}
//ServiceDemoImpl.java
package com.sdut.service;
import com.sdut.dao.UserDao;
public class ServiceDemoImpl implements ServiceDemo{
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Override
public void save() {
userDao.save();
}
}
//applicationContext.xml
<bean id="userDao" class="com.sdut.dao.UserDaoImpl" />
<bean class="com.sdut.service.ServiceDemoImpl" id="serviceDemo">
<property name="userDao" ref="userDao"/> //name = "userDao" 是setter屬性名去掉set第一個(gè)首字母變小寫(xiě)
</bean>
//通過(guò)p命名空間簡(jiǎn)化方法
<beans>
xmlns:p="http://www.springframework.org/schema/p"
<bean id="userDao" class="com.sdut.dao.UserDaoImpl" />
<bean id="serviceDemo" class="com.sdut.service.ServiceDemoImpl" p:userDao-ref="userDao"/>
</beans>
構(gòu)造方法注入
其它與上面相同
//ServiceDemoImpl.java
package com.sdut.service;
import com.sdut.dao.UserDao;
public class ServiceDemoImpl implements ServiceDemo{
private UserDao userDao;
public ServiceDemoImpl(UserDao userDao) {
this.userDao = userDao;
}
@Override
public void save() {
userDao.save();
}
}
//applicationContext.xml
<bean id="userDao1" class="com.sdut.dao.UserDaoImpl" />
<bean id="serviceDemo" class="com.sdut.service.ServiceDemoImpl">
<constructor-arg name ="userDao" ref="userDao1"></constructor-arg>
</bean>
普通數(shù)據(jù)類型注入
//ServiceDemoImpl.java
package com.sdut.service;
import com.sdut.dao.UserDao;
public class ServiceDemoImpl implements ServiceDemo{
private String username;
private int age;
public void setUsername(String username) {
this.username = username;
}
public void setAge(int age) {
this.age = age;
}
@Override
public void save() {
System.out.println("姓名:"+username+", 年齡:"+age);
}
}
//applicationContext.xml
<bean id="serviceDemo" class="com.sdut.service.ServiceDemoImpl">
<property name="username" value="張三"/>
<property name="age" value="14"/>
</bean>
集合的注入
//ServiceDemoImpl.java
package com.sdut.service;
import com.sdut.daomain.User;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
public class ServiceDemoImpl implements ServiceDemo{
private List<String> lis;
private Map<String, User> map;
private Properties properties;
public void setLis(List<String> lis) {
this.lis = lis;
}
public void setMap(Map<String, User> map) {
this.map = map;
}
public void setProperties(Properties properties) {
this.properties = properties;
}
@Override
public void save() {
System.out.println(lis);
System.out.println(properties);
Set<String> sets = map.keySet();
for(String set: sets){
System.out.println(set+" : "+map.get(set).getName()+map.get(set).getAge());
}
}
}
//applicationContext.xml
<bean id="user1" class="com.sdut.daomain.User">
<property name="name" value="張三"/>
<property name="age" value="15"/>
</bean>
<bean id="user2" class="com.sdut.daomain.User">
<property name="name" value="李四"/>
<property name="age" value="16"/>
</bean>
<bean id="serviceDemo" class="com.sdut.service.ServiceDemoImpl">
<!-- 注入數(shù)組-->
<property name="lis">
<array>
<value>aaa</value>
<value>bbb</value>
<value>ccc</value>
<value>ddd</value>
</array>
</property>
<!-- 注入map-->
<property name="map">
<map>
<entry key="name1" value-ref="user1"/>
<entry key="name2" value-ref="user2"/>
</map>
</property>
<!-- 注入配置文件-->
<property name="properties">
<props>
<prop key="name">張三</prop>
<prop key="age">14</prop>
<prop key="address">北京</prop>
</props>
</property>
</bean>
Spring 注解開(kāi)發(fā)
AOP 相關(guān)術(shù)語(yǔ)
- Target(目標(biāo)對(duì)象):代理的目標(biāo)對(duì)象
- Proxy(代理):一個(gè)類被AOP織入增強(qiáng)后,就產(chǎn)生一個(gè)結(jié)果代理類
- JoinPoint(連接點(diǎn)):被攔截到的點(diǎn)(公民)
- Pointcut(切入點(diǎn)):確定被增強(qiáng)的方法(人大代表)
- Advice:(通知):用于增強(qiáng)的方法
- Aspect(切面):切入點(diǎn)和通知的結(jié)合
- Weaving(織入):把增強(qiáng)應(yīng)用到目標(biāo)的過(guò)程
AOP開(kāi)發(fā)通知類型
通知的語(yǔ)法
<aop:通知類型 method="切面類中的方法名" pointcut="切點(diǎn)表達(dá)式"></aop:切點(diǎn)表達(dá)式>
AOP實(shí)現(xiàn)
//TargetInter.java 目標(biāo)對(duì)象接口跋核,在進(jìn)行測(cè)試依賴注入時(shí)只能通過(guò)接口接收target對(duì)象不明白(明白了岖瑰,因?yàn)?動(dòng)態(tài)代理代理的是接口所以只能通過(guò)接口接收,不能通過(guò)實(shí)現(xiàn)類接收砂代,如果通過(guò)實(shí)現(xiàn)類接收就會(huì)出現(xiàn)錯(cuò)誤)
package com.sdut.service;
public interface TargetInter {
void print();
}
//Target.java 目標(biāo)對(duì)象蹋订,被增強(qiáng)對(duì)象
package com.sdut.service;
public class Target implements TargetInter{
@Override
public void print(){
System.out.println("I am target!");
}
}
//MyAspect.java 切面類用于增強(qiáng)
package com.sdut.service;
public class MyAspect {
public void before(){
System.out.println("I am before!");
}
public void aferReturning(){
System.out.println("I am afterReturning!");
}
}
//SpringJunitTest.java 測(cè)試類
package com.sdut;
import com.sdut.service.TargetInter;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration(classes = {SpringConfiguration.class})
@ContextConfiguration("classpath:applicationContext.xml")
public class SpringJunitTest {
@Autowired
private TargetInter target;
@Test
public void text2(){
target.print();
}
}
<!--applicationContext.xml-->
<?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: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/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--目標(biāo)對(duì)象-->
<bean id="target" class="com.sdut.service.Target"/>
<!--切面對(duì)象-->
<bean id="myaspect" class="com.sdut.service.MyAspect"/>
<!--配置織入告訴Spring哪些方法(切點(diǎn))需要增強(qiáng)-->
<aop:config>
<!--聲明切面-->
<aop:aspect ref="myaspect">
<!--聲明通知的種類是before前置通知,聲明通知方法before刻伊,聲明切點(diǎn)(要被增強(qiáng)的方法)-->
<aop:before method="before" pointcut="execution(* com.sdut.service.Target.print())"/>
</aop:aspect>
</aop:config>
</beans>
切點(diǎn)表達(dá)式的抽取
<aop:config>
<!--將切點(diǎn)表達(dá)式進(jìn)行抽取-->
<aop:pointcut id="point1" expression="execution(* com.sdut.service.Target.print())"/>
<!--聲明切面-->
<aop:aspect ref="myaspect">
<!--聲明通知的種類是before前置通知露戒,聲明通知方法before,聲明切點(diǎn)(要被增強(qiáng)的方法)-->
<aop:before method="before" pointcut-ref="point1"/>
</aop:aspect>
</aop:config>
通過(guò)注解實(shí)現(xiàn)AOP
//TargetInter.java 同上
//Target.java 目標(biāo)對(duì)象捶箱,被增強(qiáng)對(duì)象
package com.sdut.service;
import org.springframework.stereotype.Component;
@Component("target")
public class Target implements TargetInter{
@Override
public void print(){
System.out.println("I am target!");
}
}
//MyAspect.java 切面類用于增強(qiáng)
package com.sdut.service;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
@Component("myaspect")
@Aspect
public class MyAspect {
@Before("execution(* com.sdut.service.Target.print())")
public void before(){
System.out.println("I am before!");
}
public void aferReturning(){
System.out.println("I am afterReturning!");
}
}
//SpringJunitTest.java 測(cè)試類 同上
<!--applicationContext.xml-->
<?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.xsd">
<context:component-scan base-package="com.sdut"/>
<aop:aspectj-autoproxy/>
</beans>
Spring中事務(wù)的管理
Java異常繼承體系
@Transactional失效場(chǎng)景
- @Transactional 應(yīng)用在非 public 修飾的方法上
- Spring默認(rèn)拋出了未檢查unchecked異常(繼承自 RuntimeException 的異常)或者 Error才回滾事務(wù)玫锋;其他異常不會(huì)觸發(fā)回滾事務(wù)。
- 異常被catch捕獲
- 開(kāi)發(fā)中避免不了會(huì)對(duì)同一個(gè)類里面的方法調(diào)用讼呢,比如有一個(gè)類Test撩鹿,它的一個(gè)方法A,A再調(diào)用本類的方法B(不論方法B是用public還是private修飾)悦屏,但方法A沒(méi)有聲明注解事務(wù)节沦,而B(niǎo)方法有。則外部調(diào)用方法A之后础爬,方法B的事務(wù)是不會(huì)起作用的甫贯。
是由于使用Spring AOP代理造成的,因?yàn)橹挥挟?dāng)事務(wù)方法被當(dāng)前類以外的代碼調(diào)用時(shí)看蚜,才會(huì)由Spring生成的代理對(duì)象來(lái)管理叫搁。
注解方式實(shí)現(xiàn)切點(diǎn)表達(dá)式的抽取
在切面類中定義一個(gè)空實(shí)現(xiàn)的方法
Pointcut("execution(* com.sdut.service.Target.print())")
public void pointcut(){}
@Before("類名.pointcut()")
public void before(){}
全注解實(shí)現(xiàn)AOP
//DruidConfiguration.java 連接數(shù)據(jù)庫(kù)相關(guān)配置類
package com.sdut.config;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;
import java.io.FileReader;
import java.util.Properties;
public class DruidConfiguration {
@Bean("dataSource")
public DataSource getDataSource(){
DataSource dataSource = null;
Properties properties = new Properties();
String file = DruidConfiguration.class.getClassLoader().getResource("druid.properties").getPath();
try {
properties.load(new FileReader(file));
dataSource = DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
assert dataSource != null;
return dataSource;
}
@Bean("jdbcTemplate")
public JdbcTemplate getJdbcTemplate(DataSource dataSource){
return new JdbcTemplate(dataSource);
}
}
//SpringConfiguration.java 主配置類
package com.sdut.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@ComponentScan("com.sdut")
@Import({DruidConfiguration.class,TransactionConfiguration.class})
@EnableTransactionManagement
public class SpringConfiguration {
}
//TransactionConfiguration.java 與事務(wù)相關(guān)的配置類
package com.sdut.config;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;
public class TransactionConfiguration {
@Bean("transactionManager")//配置事務(wù)注解驅(qū)動(dòng)
public PlatformTransactionManager createTransactionManager(DataSource dataSource){
return new DataSourceTransactionManager(dataSource);
}
}
//Transfer.java 轉(zhuǎn)賬操作接口
package com.sdut.dao.impl;
public interface Transfer {
void in(double number, int id);
void out(double number, int id);
}
//TransferImpl.java 實(shí)現(xiàn)轉(zhuǎn)賬操作
package com.sdut.dao;
import com.sdut.dao.impl.Transfer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
@Component("transferImpl")
public class TransferImpl implements Transfer {
@Autowired
private JdbcTemplate jdbctemplate ;
@Override
public void in(double number,int id) {
String sql = "update account set money=money+? where id = ?";
jdbctemplate.update(sql,number,id);
}
@Override
public void out(double number,int id) {
String sql = "update account set money=money-? where id = ?";
jdbctemplate.update(sql,number,id);
}
}
//TrasferService.java 轉(zhuǎn)賬服務(wù)接口
package com.sdut.serivice.impl;
public interface TrasferService {
void tansfer(int outid, int inid, double number);
}
//TrasferServiceImpl.java 實(shí)現(xiàn)轉(zhuǎn)賬服務(wù)
package com.sdut.serivice;
import com.sdut.dao.TransferImpl;
import com.sdut.serivice.impl.TrasferService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
@Component("trasferServiceImpl")
public class TrasferServiceImpl implements TrasferService {
@Autowired
private TransferImpl transferImpl;
@Override
@Transactional
public void tansfer(int outid, int inid, double number) {
transferImpl.out(number,outid);
//int i = 9/0;
transferImpl.in(number,inid);
}
}
//SpringJunitTest.java 測(cè)試類
package sdut;
import com.sdut.config.SpringConfiguration;
import com.sdut.serivice.impl.TrasferService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {SpringConfiguration.class})
public class SpringJunitTest {
@Autowired
private TrasferService trasferServiceImpl;
@Test
public void test() {
trasferServiceImpl.tansfer(1001,1002,500);
}
}
SpringMVC
入門(mén)級(jí)SpringMVC程序
https://wws.lanzous.com/iW21phoewda
@RequestMapping注解
參數(shù):
- value,path: 請(qǐng)求路徑
- method: 請(qǐng)求方式,參數(shù)是枚舉類渴逻,多個(gè)用{RequestMethod.get}
- params:用于指定限制請(qǐng)求參數(shù)的條件疾党,它支持簡(jiǎn)單的表達(dá)式,要求請(qǐng)求參數(shù)key和value必須和配置的一模一樣惨奕。例如 params = {"name"} 請(qǐng)求參數(shù)必須有name 雪位;params = {"name = haha"} 請(qǐng)求參數(shù)必須有name 并且值必須為haha
- headers 限制請(qǐng)求必須包含請(qǐng)求頭例如 headers = {"accept"}
請(qǐng)求參數(shù)綁定
//客戶端界面想把username和password兩個(gè)參數(shù)傳進(jìn)去
<a href="hello?username=root&password=123">進(jìn)入SpringMVC入門(mén)程序</a>
@RequestMapping("/hello") //在方法上傳入與key相同的參數(shù)
public String print(String username, String password){
System.out.println("Hello! SpringMVC");
return "success";
}
請(qǐng)求參數(shù)綁定實(shí)體類型
//User.java
package edu.sdut.domain;
public class User implements Serializable {
private String name;
private Integer age;
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
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;
}
}
//Account.java
package edu.sdut.domain;
import java.io.Serializable;
public class Account implements Serializable {
private String username;
private String password;
private Double money;
private User user;
@Override
public String toString() {
return "Account{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
", money=" + money +
", user=" + user +
'}';
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Double getMoney() {
return money;
}
public void setMoney(Double money) {
this.money = money;
}
}
//SaveController.java
package edu.sdut.controller;
import edu.sdut.domain.Account;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class SaveController {
@RequestMapping("/save") //請(qǐng)求參數(shù)綁定把數(shù)據(jù)封裝到Javabean的實(shí)體類中
public String save(Account account){
System.out.println(account);
return "success";
}
}
//index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Spring</title>
<style>
body{
text-align: center;
}
</style>
</head>
<body>
<form action="save">
用戶名:<input type="text" name="username"/> <br>
密碼:<input type="password" name="password"/> <br>
金額:<input type="text" name="money"/><br>
姓名:<input type="text" name="user.name"/><br>
年齡:<input type="text" name="user.age"/><br>
<input type="submit" value="提交">
</form>
</body>
</html>
解決客戶端提交數(shù)據(jù)中文亂碼問(wèn)題
web.xml
<!--配置過(guò)濾器解決中文亂碼問(wèn)題-->
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
自定義類型轉(zhuǎn)換器
HTML表單提交的都是String類型的數(shù)據(jù),但是我們可以直接對(duì)提交的數(shù)據(jù)進(jìn)行封裝梨撞,而不用考慮類型雹洗,這是一位Spring內(nèi)部幫我們進(jìn)行了類型轉(zhuǎn)換,例如2020/10/23卧波,其對(duì)應(yīng)的屬性如果是Date類型的話就會(huì)被轉(zhuǎn)換成Date類型數(shù)據(jù)时肿,但是2020-10-23這樣就沒(méi)有辦法進(jìn)行轉(zhuǎn)換,這時(shí)我們?nèi)绻胱屍滢D(zhuǎn)換可以自定義類型轉(zhuǎn)換器
//StringToDate.java 自定義類型轉(zhuǎn)換類繼承Conver接口港粱,重寫(xiě)convert方法
package edu.sdut.util;
import org.springframework.core.convert.converter.Converter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class StringToDate implements Converter<String, Date> {
@Override
public Date convert(String s) {
DateFormat dataFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
return dataFormat.parse(s);
} catch (ParseException e) {
throw new RuntimeException("數(shù)據(jù)類型轉(zhuǎn)換異常");
}
}
}
//springmvc.xml
<!--配置自定義類型轉(zhuǎn)換器-->
<bean id="conversionServiceFactoryBean" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="edu.sdut.util.StringToDate"/>
</set>
</property>
</bean>
<!--開(kāi)啟SpringMVC框架的注解的支持,使自定義類型轉(zhuǎn)換器生效-->
<mvc:annotation-driven conversion-service="conversionServiceFactoryBean"/>
Mybatis
編寫(xiě)sql 語(yǔ)句是用傳入?yún)?shù)#{}和${}的區(qū)別是螃成,#{}是預(yù)編譯的相當(dāng)于PrepareStatement,可以防止sql注入
lombok插件啥容,通過(guò)注解生成getter锈颗,setter顷霹,構(gòu)造方法和toString方法
按照查詢嵌套處理多對(duì)一
<mapper namespace="edu.sdut.dao.StudentDao">
<select id="findStudent" resultMap="studentTeacher">select * from student</select>
<resultMap id="studentTeacher" type="edu.sdut.domain.Student">
<!--teacher是javaBean類中的teacher字端咪惠,使其與查到的tid對(duì)應(yīng)起來(lái)-->
<association property="teacher" column="tid" javaType="edu.sdut.domain.Teacher" select="findTeacher"/>
</resultMap>
<select id="findTeacher" resultType="edu.sdut.domain.Teacher">select * from teacher</select>
</mapper>
按照結(jié)果處理多對(duì)一
<select id="findStudent2" resultMap="studentTeacher2">select s.id sid,s.`name` sname,t.`name` tname from teacher t,student s where t.id = s.tid;</select>
<resultMap id="studentTeacher2" type="edu.sdut.domain.Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="edu.sdut.domain.Teacher">
<result property="name" column="tname"/>
</association>
</resultMap>
按照查詢嵌套處理一對(duì)多
<!--按照查詢嵌套處理-->
<select id="findTeacher2" resultMap="teacherStudent2">select * from teacher where id = 1</select>
<select id="findStudent" resultType="edu.sdut.domain.Student">select * from student where tid = #{id}</select>
<resultMap id="teacherStudent2" type="edu.sdut.domain.Teacher">
<collection property="students" javaType="java.util.ArrayList" ofType="edu.sdut.domain.Student" select="findStudent" column="id"/>
</resultMap>
按照結(jié)果處理一對(duì)多
<!--處理查詢結(jié)果查詢-->
<select id="findTeacher" resultMap="teacherStudent">select t.id tid, t.`name` tname, s.id sid, s.`name` sname from student s,teacher t WHERE t.id = s.tid and t.id = 1 </select>
<resultMap id="teacherStudent" type="edu.sdut.domain.Teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<collection property="students" ofType="edu.sdut.domain.Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
</collection>
</resultMap>
小結(jié)
log4j日志工廠的使用
//導(dǎo)入相關(guān)jar包
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
//配置文件中配置
<!--配置日志工廠-->
<settings>
<!--標(biāo)準(zhǔn)日志工廠-->
<!--<setting name="logImpl" value="STDOUT_LOGGING"/>-->
<setting name="logImpl" value="LOG4J"/>
</settings>
//配置文件設(shè)置 log4j.properties
#將等級(jí)為DEBUG的日志信息輸出到console和file這兩個(gè)目的地,console和file的定義在下面的代碼
log4j.rootLogger=DEBUG,console,file
#控制臺(tái)輸出的相關(guān)設(shè)置
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%c]-%m%n
#文件輸出的相關(guān)設(shè)置
log4j.appender.file = org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./log/run.log
log4j.appender.file.MaxFileSize=10mb
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p][%d{yy-MM-dd}][%c]%m%n
#日志輸出級(jí)別
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
//簡(jiǎn)單使用
package edu.sdut.dao;
import org.apache.log4j.Logger;
import org.junit.Test;
public class LogTest {
@Test
public void test(){
Logger logger = Logger.getLogger(LogTest.class);
logger.info("info:running");
logger.debug("debug:running");
logger.error("error:running");
}
}
緩存
一級(jí)緩存是默認(rèn)開(kāi)啟的只在一次sqlSession 中有效淋淀,也就是從拿到sqlSession 到關(guān)閉之間有效