什么是ORM?
对象关系映射(Object Relational Mapping,简称ORM)模式是一种为了解决面向对象与关系数据库存在的互不匹配的现象的技术。
对应关系:一个类对应一张表,一个对象对应一行记录,一个属性对应一个字段
spring中对哪些ORM框架提供支持?
JAP(规范), hibernate(全自动,不写sql语句就实现增删改查), mybatis(半自动)
JPA规范:规范
做一个项目的增删改查
新建数据库
新建一张表
给表元素填上相应的值
在IDEA新建一个多模块ORM,并建立相关的包
添加相关的依赖包
<?xml version="1.0" encoding="UTF-8"?>
<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.spring</groupId>
<artifactId>orm</artifactId>
<version>1.0-SNAPSHOT</version>
<name>orm</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<spring.version>5.1.5.RELEASE</spring.version>
<aspectj.version>1.9.2</aspectj.version>
<junit.version>4.12</junit.version>
<log4j.version>1.2.17</log4j.version>
<slf4j.version>1.7.12</slf4j.version>
<mysql.version>5.1.47</mysql.version>
<mybatis.version>3.5.0</mybatis.version>
<mybatis-spring.version>2.0.0</mybatis-spring.version>
<tk-mybatis.version>4.1.5</tk-mybatis.version>
<druid.version>1.1.14</druid.version>
<lombok.version>1.18.6</lombok.version>
</properties>
<dependencies>
<!--Spring相关依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<!--mysql依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!--mybatis依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!--mybatis-spring依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis-spring.version}</version>
</dependency>
<!--通用mapper依赖-->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>${tk-mybatis.version}</version>
</dependency>
<!--druid连接池依赖-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
<!--lombok依赖-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<!--junit依赖-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<!-- log4j日志依赖 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
</dependencies>
<build>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
<!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
<plugin>
<artifactId>maven-site-plugin</artifactId>
<version>3.7.1</version>
</plugin>
<plugin>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>3.0.0</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
jdbc.properties文件
log4j.rootLogger=debug, stdout,file
#debug与info
#debug较详细,info比较简单
##设置日志记录到控制台的方式
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %5p %c{1}:%L - %m%n
##设置日志记录到文件的方式
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=logs/my_log.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %5p %c{1}:%L - %m%n
配置spring_batis.xml类
<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"
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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--读入外部数据库连接属性文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--扫描Service包的组件-->
<context:component-scan base-package="com.spring.orm.service"/>
<!--通过druid配置数据源-->
<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="initialSize" value="20"/>
<!-- 连接池最大使用连接数量 -->
<property name="maxActive" value="20"/>
<!-- 连接池最小空闲 -->
<property name="minIdle" value="0"/>
<!-- 配置获取连接等待超时的时间 -->
<property name="maxWait" value="60000"/>
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000"/>
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="300000"/>
<!-- 连接空闲时测试是否有效 -->
<property name="testWhileIdle" value="false"/>
<!-- 获取连接时测试是否有效 -->
<property name="testOnBorrow" value="false"/>
<!-- 归还连接时是否测试有效 -->
<property name="testOnReturn" value="false"/>
<!-- 打开PSCache缓存,并且指定每个连接上PSCache的大小 -->
<property name="poolPreparedStatements" value="true"/>
<property name="maxPoolPreparedStatementPerConnectionSize" value="20"/>
</bean>
<!-- 配置mybatis的Session -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="typeAliasesPackage" value="com.spring.orm.entity"/>
</bean>
<!-- 配置通用Mapper -->
<bean class="tk.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.spring.orm.dao"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<property name="markerInterface" value="com.spring.orm.dao.BaseDAO"/>
<property name="properties">
<value>
mappers = com.spring.orm.dao.BaseDAO
IDENTITY = MYSQL
</value>
</property>
</bean>
<!--事务管理bean -->
<bean id="manager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 使用声明式事务 -->
<tx:annotation-driven transaction-manager="manager"/>
</beans>
User类
package com.spring.orm.entity;
import lombok.Data;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Table(name = "t_user")
@Data
public class User {
// 标记主键和主键策略
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String account;
private String password;
private Integer credits;
}
BaseDAO接口
package com.spring.orm.dao;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;
//通用dao接口
public interface BaseDAO<T> extends Mapper<T>, MySqlMapper<T> {
}
UserDao接口
package com.spring.orm.dao;
import com.spring.orm.entity.User;
/**UserDAO,继承通用DAO接口基础的CRUD功能
*/
public interface UserDAO extends BaseDAO<User> {
}
UserService类
package com.spring.orm.service;
import com.spring.orm.entity.User;
import java.util.List;
public interface UserService {
/**
* 新增用户
*
* @param user
* @return
*/
int insertUser(User user);
/**
* 根据id删除用户
*
* @param id
* @return
*/
int deleteUser(long id);
/**
* 更新用户
*
* @param user
* @return
*/
int updateUser(User user);
/**
* 查询所有用户
*
* @return
*/
List<User> selectUsers();
/**
* 根据id查询用户
*
* @param id
* @return
*/
User getUser(long id);
}
UserServiceImpl类
package com.spring.orm.service.impl;
import com.spring.orm.dao.UserDAO;
import com.spring.orm.entity.User;
import com.spring.orm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
@Transactional
public class UserServiceImpl implements UserService {
@Autowired
private UserDAO userDAO;
@Override
public int insertUser(User user) {
return userDAO.insert(user);
}
@Override
public int deleteUser(long id) {
return userDAO.deleteByPrimaryKey(id);
}
@Override
public int updateUser(User user) {
return userDAO.updateByPrimaryKey(user);
}
@Override
public List<User> selectUsers() {
return userDAO.selectAll();
}
@Override
public User getUser(long id) {
return userDAO.selectByPrimaryKey(id);
}
}
UserServiceImplText类
import com.spring.orm.entity.User;
import com.spring.orm.service.UserService;
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 java.util.List;
import static org.junit.Assert.*;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/spring_mybatis.xml"})
public class UserServiceImplTest {
@Autowired
private UserService userService;
@Test
public void insertUser() {
User user = new User();
user.setAccount("eee");
user.setPassword("456");
user.setCredits(666);
int n = userService.insertUser(user);
assertEquals(1, n);
}
@Test
public void deleteUser() {
int n = userService.deleteUser(2);
assertEquals(1,n);
}
@Test
public void updateUser() {
User user = userService.getUser(2);
user.setPassword("123");
user.setCredits(100);
int n = userService.updateUser(user);
assertEquals(1, n);
}
@Test
public void selectUsers() {
List<User> users = userService.selectUsers();
users.forEach(user -> System.out.println(user));
}
@Test
public void getUser() {
User user = userService.getUser(1);
System.out.println(user);
}
}
有时候会出现一些错误,就看看是不是配置或者数据库名字错了