使用注解,更加简单
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.gem.demo</groupId>
<artifactId>spring-mybatis-xml-annotation</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<!-- mybatis -->
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<!-- 坐标 -->
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.1</version>
</dependency>
<!-- 数据库驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.17</version>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
<scope>provided</scope>
</dependency>
<!-- 单元测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- spring核心 -->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.2.2.RELEASE</version>
</dependency>
<!-- 单元测试 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.2.RELEASE</version>
</dependency>
<!-- spring整合mybatis jar -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.7.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->
<!-- 分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.2</version>
</dependency>
</dependencies>
</project>
数据库的相关信息:db.properties文件上的配置
#配置数据库信息
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/homeworkonline?serverTimezone=Asia/Shanghai
jdbc.username=root
jdbc.password=root
#配置连接池信息
jdbc.initialSize=10
jdbc.maxTotal=5
jdbc.maxIdle=5
jdbc.maxWaitMillis=5000
打印日志的相关信息,log4j,properties文件上的配置
#打印日志级别
log4j.rootLogger=debug, stdout
# 控制台输出日志
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
实体类 book
package com.hadwinling.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Book {
private int bid;
private String bno;
private String bname;
private String author;
private double price;
private String mark;
public Book(String bno, String bname, String author, double price, String mark) {
this.bno = bno;
this.bname = bname;
this.author = author;
this.price = price;
this.mark = mark;
}
}
核心:AppConfig.java文件
package com.hadwinling;
import javax.sql.DataSource;
import org.apache.commons.dbcp2.BasicDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@ComponentScan
@EnableAspectJAutoProxy
@EnableTransactionManagement
@PropertySource("classpath:db.properties")
//mapper扫描器 为Mapper接口生成实现类
@MapperScan(basePackages="com.hadwinling.mapper")
public class AppConfig {
@Autowired
Environment env;
@Bean
public DataSource dataSource() {
BasicDataSource bds=new BasicDataSource();
bds.setDriverClassName(env.getProperty("jdbc.driver"));
bds.setUrl(env.getProperty("jdbc.url"));
bds.setUsername(env.getProperty("jdbc.username"));
bds.setPassword(env.getProperty("jdbc.password"));
bds.setInitialSize(Integer.parseInt(env.getProperty("jdbc.initialSize")));
bds.setMaxTotal(Integer.parseInt(env.getProperty("jdbc.maxTotal")));
bds.setMaxIdle(Integer.parseInt(env.getProperty("jdbc.maxIdle")));
bds.setMaxWaitMillis(Integer.parseInt(env.getProperty("jdbc.maxWaitMillis")));
return bds;
}
@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean() {
SqlSessionFactoryBean sqlSessionFactoryBean=new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource());
//加载MyBatis配置文件
// sqlSessionFactoryBean.setConfigLocation(new ClassPathResource("SqlMapConfig.xml"));
//Spring整合MyBatis[MyBatis配置文件不需要]
sqlSessionFactoryBean.setTypeAliasesPackage("com.hadwinling.entity");
// sqlSessionFactoryBean.setPlugins(plugins);//配置插件
return sqlSessionFactoryBean;
}
@Bean
public DataSourceTransactionManager transactionManager() {
DataSourceTransactionManager transactionManager=new DataSourceTransactionManager();
transactionManager.setDataSource(dataSource());
return transactionManager;
}
}
BookMapper.java使用注解实现MyBatis
package com.hadwinling.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.SelectKey;
import org.apache.ibatis.annotations.Update;
import com.hadwinling.entity.Book;
public interface BookMapper {
//查询所有书籍
@Select ("select * from book")
List<Book> findBooks();
// 删除书籍,通过书籍编号删除
@Delete("delete from book where bno =#{bno}")
int deleteBook(String bno);
//新增书籍
@Insert ("insert into book (bno,bname,author,price,mark) values (#{bno},#{bname},#{author},#{price},#{mark})")
@SelectKey(keyColumn = "id", // 查询列
keyProperty = "id", // 实体属性
before = false, // 在新增之后
resultType = Integer.class, // statement的查询结果类型
statement = { "select last_insert_id()" }// 新增记录之后做的 sql语语句,查询最后一个id值
)
int addBook(Book book);
// 修改书籍信息
@Update("update book set bno=#{bno},bname=#{bname},author=#{author},price=#{price},remark=#{remark} where id=#{id}")
int updateBook(Book book);
//按照书名模糊查询
@Select("select * from book where bname like '%${value}%'")
List<Book> findBookByBname(String bname);
}
BookSevice
package com.hadwinling.service;
import java.util.List;
import com.hadwinling.entity.Book;
public interface BookService {
// 查找所有书籍
List<Book> findBooks();
// 删除书籍,通过书籍编号删除
int deleteBooks(String bno);
// 新增书籍
int addBook(Book book);
// 修改书籍信息
int updateBook(Book book);
// 按照书名模糊查询
List<Book> findBookByBname(String bname);
}
bookServiceImpl
package com.hadwinling.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.hadwinling.entity.Book;
import com.hadwinling.mapper.BookMapper;
import com.hadwinling.service.BookService;
@Service
@Transactional
public class BookServiceImpl implements BookService {
@Autowired
private BookMapper bookMapper;
@Override
public List<Book> findBooks() {
// TODO Auto-generated method stub
return bookMapper.findBooks();
}
@Override
public int deleteBooks(String bno) {
// TODO Auto-generated method stub
return bookMapper.deleteBook(bno);
}
@Override
public int addBook(Book book) {
// TODO Auto-generated method stub
return bookMapper.addBook(book);
}
@Override
public int updateBook(Book book) {
// TODO Auto-generated method stub
return bookMapper.updateBook(book);
}
@Override
public List<Book> findBookByBname(String bname) {
// TODO Auto-generated method stub
return bookMapper.findBookByBname(bname);
}
}
测试类:这里使用单元测试类
BaseTest文件的配置:
package com.hadwinling;
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.hadwinling.mapper.BookMapper;
import com.hadwinling.service.BookService;
@ContextConfiguration(locations = "classpath:applicationContext.xml")
@RunWith(SpringJUnit4ClassRunner.class)
public class BaseTest {
@Autowired
protected BookMapper bookMapper;
@Autowired
protected BookService bookService;
}
serviceTest文件的配置:
package com.hadwinling.service;
import java.util.List;
import java.util.Scanner;
import org.junit.Test;
import com.hadwinling.BaseTest;
import com.hadwinling.entity.Book;
public class ServiceTest extends BaseTest {
Scanner input = new Scanner(System.in);
// @Test
// public void findBook() {
// List<Book> books = bookMapper.findBooks();
// for (Book book : books) {
// System.out.println(book);
// }
// }
// @Test
// public void deleteBook() {
// System.out.println("请输入要删除的书籍编号");
// String bno= input.next();
// int result = bookMapper.deleteBook(bno);
// System.out.println(result);
// }
// @Test
// public void addBook() {
// System.out.println("请输入书籍编号");
// String bno = input.next();
// System.out.println("请输入书名");
// String bname = input.next();
// System.out.println("请输入作者");
// String author = input.next();
// System.out.println("请输入价格");
// int price = input.nextInt();
// System.out.println("请输入评价");
// String mark = input.next();
// Book book = new Book(bno, bname, author, price, mark);
// int result = bookMapper.addBook(book);
// System.out.println(result);
// }
// @Test
// public void updateBook() {
// System.out.println("请输入书籍编号");
// String bno = input.next();
// System.out.println("请输入书名");
// String bname = input.next();
// System.out.println("请输入作者");
// String author = input.next();
// System.out.println("请输入价格");
// int price = input.nextInt();
// System.out.println("请输入评价");
// String mark = input.next();
// Book book = new Book(bno, bname, author, price, mark);
// int result = bookMapper.updateBook(book);
// System.out.println(result);
// }
@Test
public void findBookByBname() {
System.out.println("输入书名");
String bname = input.next();
List<Book> books = bookMapper.findBookByBname(bname);
for (Book book : books) {
System.out.println(book);
}
}
}