大家好,又见面了,我是你们的朋友全栈君。
ORM: 对象关系映射(Object Relational Mapping,简称ORM)模式是一种为了解决面向对象与关系数据库存在的互不匹配的现象的技术。简单的说,ORM是通过使用描述对象和数据库之间映射的元数据,将程序中的对象自动持久化到关系数据库中。那么,到底如何实现持久化呢?一种简单的方案是采用硬编码方式,为每一种可能的数据库访问操作提供单独的方法。
- 这种方案存在以下不足:
1.持久化层缺乏弹性。一旦出现业务需求的变更,就必须修改持久化层的接口
2.持久化层同时与域模型与关系数据库模型绑定,不管域模型还是关系数据库模型发生变化,毒药修改持久化曾的相关程序代码,增加了软件的维护难度。
ORM提供了实现持久化层的另一种模式,它采用映射元数据来描述对象关系的映射,使得ORM中间件能在任何一个应用的业务逻辑层和数据库层之间充当桥梁。Java典型的ORM中间件有:Hibernate,ibatis,speedframework。
- ORM的方法论基于三个核心原则:
· 简单:以最基本的形式建模数据。
· 传达性:数据库结构被任何人都能理解的语言文档化。
· 精确性:基于数据模型创建正确标准化了的结构。
代码展示:
目录结构:
pom.xml
<?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>groupId</groupId>
<artifactId>Demo01</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.2</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
</dependencies>
</project>
User.java
package com.xbj.po;
public class User {
private Integer id;
private String username;
private String password;
private Integer age;
//get set toString
}
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" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--导入配置文件-->
<context:property-placeholder location="classpath:db.properties" />
<!--1.数据源-->
<bean class="com.mchange.v2.c3p0.ComboPooledDataSource" id="dataSource">
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="driverClass" value="${jdbc.driver}" />
<property name="user" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<context:component-scan base-package="com.xbj.dao.impl" />
<!--1. 配置事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 通知 映射到上面的事务管理器-->
<tx:advice transaction-manager="transactionManager" id="transactionInterceptor">
<tx:attributes>
<tx:method name="add*" />
<tx:method name="insert*"/>
<tx:method name="save*"/>
<tx:method name="update*"/>
<tx:method name="change*" />
<tx:method name="del*"/>
<tx:method name="remove*"/>
<tx:method name="drop*"/>
</tx:attributes>
</tx:advice>
<!-- aop切面并配置切入点入进行事物管理 指向上面的映射 -->
<aop:config>
<aop:advisor advice-ref="transactionInterceptor" pointcut="execution(* com.xbj.service.impl.*.*(..))" />
</aop:config>
</beans>
db.properties
jdbc.url=jdbc:mysql://localhost:3306/db1
jdbc.driver=com.mysql.jdbc.Driver
jdbc.username=root
jdbc.password=root
UserDAO.java
package com.xbj.dao;
import com.xbj.po.User;
import java.util.List;
public interface UserDAO {
void addUser(User user);
void delUser(Integer id);
void updateUser(User user);
User findUserById(Integer id);
List<User> findAll();
User findUserById2(Integer id);
}
UserDAOImpl.java
package com.xbj.dao.impl;
import com.xbj.dao.UserDAO;
import com.xbj.po.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;
import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
@Repository
public class UserDAOImpl extends JdbcDaoSupport implements UserDAO {
@Resource
public void init(DataSource dataSource){
super.setDataSource(dataSource);
}
public void addUser(User user) {
//String sql, @Nullable Object... args
String sql = "INSERT INTO t_user VALUES (NULL,?,?,?)";
this.getJdbcTemplate().update(sql, user.getUsername(), user.getPassword(), user.getAge());
}
public void delUser(Integer id) {
String sql = "DELETE FROM t_user WHERE id=?";
this.getJdbcTemplate().update(sql, id);
}
public void updateUser(User user) {
String sql = "UPDATE t_user SET username=? ,password=?,age=? WHERE id=?";
this.getJdbcTemplate().update(sql, user.getUsername(), user.getPassword(), user.getAge(), user.getId());
}
//自动映射,但要保证User类中的字段名与数据库的要一致
public User findUserById(Integer id) {
String sql = "SELECT * FROM t_user WHERE id=?";
List<User> list = this.getJdbcTemplate().query(sql, new BeanPropertyRowMapper<User>(User.class), id);
return list.size() > 0 ? list.get(0) : null;
}
public List<User> findAll() {
String sql = "SELECT * FROM t_user";
return this.getJdbcTemplate().query(sql, new BeanPropertyRowMapper<User>(User.class));
}
//手动映射
public User findUserById2(Integer id) {
String sql = "SELECT * FROM t_user WHERE id=?";
return this.getJdbcTemplate().query(sql, new ResultSetExtractor<User>() {
public User extractData(ResultSet rs) throws SQLException, DataAccessException {
User user=new User();
if(rs.next()){
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("pwd"));
user.setAge(rs.getInt("age"));
}
return user;
}
}, id);
}
}
原生测试方法:
package com.xbj;
import org.junit.Test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Test01 {
@Test
public void t1() throws Exception {
Class.forName("com.mysql.jdbc.Driver");
//DriverManager JDBC大管家
Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/db1","root","root");
PreparedStatement psmt=connection.prepareStatement("SELECT * from t_user WHERE age > ?");
psmt.setInt(1,33);
ResultSet rs=psmt.executeQuery();
while (rs.next()){
Integer id= rs.getInt("id");
String username=rs.getString("username");
System.out.println(id+"--"+username);
}
}
}
Spring测试方法;
package com.xbj;
import com.xbj.dao.UserDAO;
import com.xbj.po.User;
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;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
"classpath:applicationContext.xml"})
public class Test02 {
@Autowired
private UserDAO userDAO;
@Test
public void t1(){
List<User> users=userDAO.findAll();
for (User user:users){
System.out.println(user);
}
}
@Test
public void t2(){
User user=userDAO.findUserById(8);
System.out.println(user);
}
@Test
public void t3(){
User user=new User();
user.setUsername("hanmeimei");
user.setPassword("ok");
user.setAge(16);
userDAO.addUser(user);
}
@Test
public void t4(){
User user=userDAO.findUserById(5);
user.setUsername("HMM");
userDAO.updateUser(user);
}
@Test
public void t5(){
userDAO.delUser(5);
}
@Test
public void t6(){
User user= userDAO.findUserById2(2);
System.out.println(user);
}
}
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/106634.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...