需要導入的包
環境搭建
pojo類
package com. ywq. ssm. pojo;
public class User {
private Integer id ;
private String name;
private String password;
private Integer age;
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 String getPassword ( ) {
return password;
}
public void setPassword ( String password) {
this . password = password;
}
public Integer getAge ( ) {
return age;
}
public void setAge ( Integer age) {
this . age = age;
}
public User ( Integer id, String name, String password, Integer age) {
super ( ) ;
this . id = id;
this . name = name;
this . password = password;
this . age = age;
}
public User ( ) {
super ( ) ;
}
@Override
public String toString ( ) {
return "User [id=" + id + ", name=" + name + ", password=" + password + ", age=" + age + "]" ;
}
}
mapper接口
package com. ywq. ssm. mapper;
import com. ywq. ssm. pojo. User;
public interface UserMapper {
int insert ( User user) ;
User selectByPrimaryKey ( Integer id) ;
}
mapper.xml配置
< ? 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.ywq.ssm.mapper.UserMapper" >
< insert id= "insert" parameterType= "User" keyColumn= "id"
keyProperty= "id" useGeneratedKeys= "true" >
insert into user ( name, password, age) values ( #{ name} , #{ password} , #{ age} )
< / insert>
< select id= "selectByPrimaryKey" parameterType= "Integer"
resultType= "User" >
select * from user where id = #{ id}
< / select>
< / mapper>
Service接口
package com. ywq. ssm. service;
import com. ywq. ssm. pojo. User;
public interface UserService {
int insert ( User user) ;
User selectByPrimaryKey ( Integer id) ;
}
Service實現類
package com. ywq. ssm. service. impl;
import org. springframework. beans. factory. annotation. Autowired;
import org. springframework. stereotype. Service;
import com. ywq. ssm. mapper. UserMapper;
import com. ywq. ssm. pojo. User;
import com. ywq. ssm. service. UserService;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper UserMapper;
@Override
public int insert ( User user) {
return UserMapper. insert ( user) ;
}
@Override
public User selectByPrimaryKey ( Integer id) {
return UserMapper. selectByPrimaryKey ( id) ;
}
}
db.properties文件
jdbc. driverClassName= com. mysql. jdbc. Driver
jdbc. url= jdbc: mysql: / / localhost: 3306 / mybatis? characterEncoding= utf- 8
jdbc. username= root
jdbc. password= root
jdbc. maxActive= 20
log4j.properties文件
# Global logging configuration
log4j. rootLogger= ERROR, stdout
# MyBatis logging configuration. . .
# 配置日誌
# 規則 log4j. logger. 映射接口的包= 日誌級別
# 總共五個級別(error: 錯誤, info:普通信息, debug:調試信息, warn:警告, trae/ all:所有情況)
# 當前開發階段配置debug/ ( all/ trace) , 項目上線以後配置error
log4j. logger. com. ywq. ssm. mapper= TRACE
# Console output. . .
log4j. appender. stdout= org. apache. log4j. ConsoleAppender
log4j. appender. stdout. layout= org. apache. log4j. PatternLayout
log4j. appender. stdout. layout. ConversionPattern= % 5 p [ % t] - % m% n
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: tx= "http://www.springframework.org/schema/tx"
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- 4.3 . xsd
http: / / www. springframework. org/ schema/ aop http: / / www. springframework. org/ schema/ aop/ spring- aop- 4.3 . xsd
http: / / www. springframework. org/ schema/ tx http: / / www. springframework. org/ schema/ tx/ spring- tx- 4.3 . xsd">
< ! -- 配置包掃描位置 -- >
< context: component- scan base- package = "com.ywq.ssm" / >
< ! -- 讀取數據庫配置文件 -- >
< context: property- placeholder location= "classpath:db.properties" / >
< ! -- 配置阿里巴巴連接池 -- >
< bean id= "dataSource" class = "com.alibaba.druid.pool.DruidDataSource"
init- method= "init" destroy- method= "close" >
< property name= "driverClassName" value= "${jdbc.driverClassName}" / >
< property name= "url" value= "${jdbc.url}" / >
< property name= "username" value= "${jdbc.username}" / >
< property name= "password" value= "${jdbc.password}" / >
< property name= "maxActive" value= "${jdbc.maxActive}" / >
< / bean>
< ! -- 配置SqlSessionFactoryBean -- >
< bean id= "sqlSessionFactor" class = "org.mybatis.spring.SqlSessionFactoryBean" >
< ! -- 配置數據源 -- >
< property name= "dataSource" ref= "dataSource" / >
< ! -- 讀取映射接口對應的映射文件 【可選】,底層自動綁定接口映射文件,理論上可以不用配-- >
< property name= "mapperLocations" >
< array>
< ! -- 讀取單個映射文件 -- >
< ! -- < value> classpath: com/ ywq/ ssm/ mapper/ UserMapper. xml< / value> -- >
< ! -- 讀取所有映射文件:* 通配符 -- >
< value> classpath: com/ ywq/ ssm/ mapper
純註解配置代碼
package com. ywq. ssm;
import javax. sql. DataSource;
import org. apache. ibatis. annotations. Mapper;
import org. apache. ibatis. session. SqlSessionFactory;
import org. mybatis. spring. SqlSessionFactoryBean;
import org. mybatis. spring. annotation. MapperScan;
import org. springframework. beans. factory. annotation. Value;
import org. springframework. context. annotation. Bean;
import org. springframework. context. annotation. ComponentScan;
import org. springframework. context. annotation. Configuration;
import org. springframework. context. annotation. PropertySource;
import org. springframework. context. annotation. Scope;
import org. springframework. jdbc. core. JdbcTemplate;
import org. springframework. jdbc. datasource. DataSourceTransactionManager;
import org. springframework. transaction. PlatformTransactionManager;
import org. springframework. transaction. annotation. EnableTransactionManagement;
import com. alibaba. druid. pool. DruidDataSource;
@Configuration
@ComponentScan ( "com.ywq.ssm" )
@PropertySource ( "classpath:db.properties" )
@EnableTransactionManagement
@MapperScan ( "com.ywq.ssm.mapper" )
public class SpringConfig {
@Value ( "${jdbc.driverClassName}" )
private String driverClassName;
@Value ( "${jdbc.url}" )
private String url;
@Value ( "${jdbc.username}" )
private String username;
@Value ( "${jdbc.password}" )
private String password;
@Value ( "${jdbc.maxActive}" )
private Integer maxActive;
@Bean ( name = "dataSource" , initMethod = "init" , destroyMethod = "close" )
@Scope ( "singleton" )
public DataSource getDataSource ( ) {
System. out. println ( "連接池已創建。。" ) ;
DruidDataSource ds = new DruidDataSource ( ) ;
ds. setDriverClassName ( driverClassName) ;
ds. setUrl ( url) ;
ds. setUsername ( username) ;
ds. setPassword ( password) ;
ds. setMaxActive ( maxActive) ;
return ds;
}
@Bean
public SqlSessionFactoryBean getFactory ( ) throws Exception {
System. out. println ( "SqlSessionFactory創建了.." ) ;
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean ( ) ;
sqlSessionFactoryBean. setDataSource ( getDataSource ( ) ) ;
sqlSessionFactoryBean. setTypeAliasesPackage ( "com.ywq.ssm.pojo" ) ;
SqlSessionFactory object = sqlSessionFactoryBean. getObject ( ) ;
return sqlSessionFactoryBean;
}
@Bean
public PlatformTransactionManager getTxManager ( ) {
return new DataSourceTransactionManager ( getDataSource ( ) ) ;
}
}
測試代碼
package com. ywq. ssm. test;
import static org. junit. Assert. *;
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;
import com. ywq. ssm. SpringConfig;
import com. ywq. ssm. pojo. User;
import com. ywq. ssm. service. UserService;
@RunWith ( SpringJUnit4ClassRunner. class )
@ContextConfiguration ( classes = SpringConfig. class )
public class UserServiceTest {
@Autowired
private UserService userService;
@Test
public void testInsert ( ) {
User user = new User ( null, "李兵" , "152" , 22 ) ;
int row = userService. insert ( user) ;
System. out. println ( row) ;
}
@Test
public void testSelectByPrimaryKey ( ) {
User user = userService. selectByPrimaryKey ( 12 ) ;
System. out. println ( "user:" + user) ;
}
}