Spring笔记05(Spring JDBC三种数据源和ORM框架的映射)

本文内容纲要:

- 1.ORM框架的映射

- 01.JDBC连接数据库以前的方式代码,并给对象赋值

- 02.我们使用反射机制来 动态的给 Student对象赋值

- 2.Spring的JDBC:

- 01.实体类代码:

- 02.dao层代码:

- 03.service层代码:

- 04.连接数据库的properties文件:jdbc.properties

- 05.applicationContext.xml文件:

- 06.测试代码:

1.ORM框架的映射

01.JDBC连接数据库以前的方式代码,并给对象赋值

@Test

/**

* 以前的方式jdbc

*/

public void TestJdbc(){

/**

* 连接数据库的四要素

*/

String driver="com.mysql.jdbc.Driver";

String url="jdbc:mysql://localhost:3306/spring";

String username="root";

String password="666888";

/**

* 创建jdbc需要的api

*/

Connection connection=null;

PreparedStatement pst=null;

ResultSet rs=null;

try {

//01加载驱动

Class.forName(driver);

//02获取链接

connection= DriverManager.getConnection(url, username, password);

//03书写sql语句

String sql="select sid,sname,age from student where sid=?";

//04给参数赋值

pst=connection.prepareStatement(sql);

pst.setInt(1,2);

//05获取查询结果

rs=pst.executeQuery();

while(rs.next()){

Student student=new Student();

student.setSid(rs.getInt("sid"));

student.setAge(rs.getInt("age"));

student.setSname(rs.getString("sname"));

System.out.println(student);

}

} catch (Exception e) {

e.printStackTrace();

}finally{

try {

rs.close();

pst.close();

connection.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

}

02.我们使用反射机制来 动态的给 Student对象赋值

/**

* 我们使用反射机制来 动态的给 Student对象赋值

*/

public static void main(String[] args){

/**

* 连接数据库的四要素

*/

String driver="com.mysql.jdbc.Driver";

String url="jdbc:mysql://localhost:3306/spring";

String username="root";

String password="666888";

/**

* 创建jdbc需要的api

*/

Connection connection=null;

PreparedStatement pst=null;

ResultSet rs=null;

//创建需要映射的实体类

Object student=null;

try {

student=Class.forName("cn.pb.bean.Student").newInstance();

} catch (Exception e) {

e.printStackTrace();

}

try {

//01.加载驱动

Class.forName(driver);

//02.获取连接

connection=DriverManager.getConnection(url,username,password);

//03.书写sql语句

String sql="select sid,age,sname from student where sid=?";

//04.给参数赋值

pst=connection.prepareStatement(sql);

pst.setInt(1,3);

//05.返回结果

rs=pst.executeQuery();

while (rs.next()){

//获取元数据的结果集 元数据:描述数据的数据

ResultSetMetaData metaData = rs.getMetaData();

System.out.println("元数据"+metaData);

int columnCount = metaData.getColumnCount();

//遍历元数据集合

for (int i=1;i<=columnCount;i++){

//获取数据库字段的名称

String columnName = metaData.getColumnName(i);

//获取数据库字段的类型 返回的类型都是大写

String columnTypeName = metaData.getColumnTypeName(i);

/**

* 01.给我一个元数据的名称

* 02.我去实体类中找对应的setXxx()

*/

String method = getMethod(columnName);

//赋值的时候根据类型

if(columnTypeName.equals("INT")){

student.getClass().getMethod(method,int.class).invoke(student,rs.getInt(columnName));

}else if(columnTypeName.equals("VARCHAR")){

student.getClass().getMethod(method,String.class).invoke(student,rs.getString(columnName));

}

}

Student stu= (Student) student;

System.out.println(stu);

}

} catch (Exception e) {

e.printStackTrace();

}finally {

try {

rs.close();

pst.close();

connection.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

}

/**

* 01.用户给我一个字段名称(数据库中)

* 02.我们返回一个set+字段名 (首字母大写)

* @param name 字段名称

* @return 返回的set方法名称

*/

public static String getMethod(String name){//传过来sid 返回 setSid

return "set"+name.substring(0,1).toUpperCase()+name.substring(1);

}

2.Spring的JDBC:

01.实体类代码:

package cn.pb.bean;

/**

* student的实体类

*/

public class Student {

private int sid;

private int age;

private String sname;

public Student(int sid, int age, String sname) {

this.sid = sid;

this.age = age;

this.sname = sname;

}

public Student(int age, String sname) {

this.age = age;

this.sname = sname;

}

public Student() {

}

public int getSid() {

return sid;

}

public void setSid(int sid) {

this.sid = sid;

}

public int getAge() {

return age;

}

public void setAge(int age) {

this.age = age;

}

public String getSname() {

return sname;

}

public void setSname(String sname) {

this.sname = sname;

}

@Override

public String toString() {

return "Student{" +

"sid=" + sid +

", age=" + age +

", sname='" + sname + '\'' +

'}';

}

}

02.dao层代码:

001.dao层代码

package cn.pb.dao;

import cn.pb.bean.Student;

import java.util.List;

public interface StudentDao {

int addStudent(Student student);

int delStudent(Student student);

int updateStudent(Student student);

List<Student> findAllStudents();

}

002.daoImpl层代码

package cn.pb.dao.impl;

import cn.pb.bean.Student;

import cn.pb.dao.StudentDao;

import org.springframework.jdbc.core.RowMapper;

import org.springframework.jdbc.core.support.JdbcDaoSupport;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.List;

/**

* Spring 有一个类叫 JdbcDaoSupport ===>BaseDao

* JdbcDaoSupport有一个属性叫JdbcTemplate

* 在创建JdbcTemplate的时候 需要一个DataSource

*

* 我们只需要在配置文件中 配置数据源 即可!

*

*/

public class StudentDaoImpl extends JdbcDaoSupport implements StudentDao {

public int addStudent(Student student) {

String sql="insert into student(sname,age) values(?,?)";

return getJdbcTemplate().update(sql,student.getSname(),student.getAge());

}

public int delStudent(Student student) {

String sql="delete from student where sid=?";

return getJdbcTemplate().update(sql,student.getSid());

}

public int updateStudent(Student student) {

String sql="update student set sname=?,age=? where sid=?";

return getJdbcTemplate().update(sql,student.getSname(),student.getAge(),student.getSid());

}

/**

* @return 行映射器 rowMapper

*/

public List<Student> findAllStudents() {

String sql="select * from student";

return getJdbcTemplate().query(sql, new StudentRowMapper() {

});

}

}

行映射器代码:

package cn.pb.dao.impl;

import cn.pb.bean.Student;

import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;

import java.sql.SQLException;

public class StudentRowMapper implements RowMapper<Student> {

/**

*

* @param resultSet 之前叫 返回数据的结果集,是所有数据

* 现在 这个不是所有,是一行数据的结果集

*/

public Student mapRow(ResultSet resultSet, int i) throws SQLException {

Student student=new Student();

student.setSid(resultSet.getInt("sid"));

student.setSname(resultSet.getString("sname"));

student.setAge(resultSet.getInt("age"));

return student;

}

}

03.service层代码:

001.service层代码:

package cn.pb.service;

import cn.pb.bean.Student;

import java.util.List;

public interface StudentService {

int addStudent(Student student);

int delStudent(Student student);

int updateStudent(Student student);

List<Student> findAllStudents();

}

002.serviceImpl层代码

package cn.pb.service.impl;

import cn.pb.bean.Student;

import cn.pb.dao.StudentDao;

import cn.pb.service.StudentService;

import java.util.List;

public class StudentServiceImpl implements StudentService {

private StudentDao dao;

public int addStudent(Student student) {

return dao.addStudent(student);

}

public int delStudent(Student student) {

return dao.delStudent(student);

}

public int updateStudent(Student student) {

return dao.updateStudent(student);

}

public List<Student> findAllStudents() {

return dao.findAllStudents();

}

public StudentDao getDao() {

return dao;

}

public void setDao(StudentDao dao) {

this.dao = dao;

}

}

04.连接数据库的properties文件:jdbc.properties

jdbc.driverClass=com.mysql.jdbc.Driver

jdbc.jdbcUrl=jdbc:mysql://localhost:3306/spring

jdbc.userName=root

jdbc.password=666888

05.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:p="http://www.springframework.org/schema/p"

xmlns:c="http://www.springframework.org/schema/c"

xmlns:context="http://www.springframework.org/schema/context"

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">

<!--01.加载jdbc.properties文件-->

<context:property-placeholder location="classpath:jdbc.properties"/>

<!--02.配置数据源-->

<!--001.使用spring默认的数据源

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">

<property name="driverClassName" value="${jdbc.driverClass}"/>

<property name="url" value="${jdbc.jdbcUrl}"/>

<property name="username" value="${jdbc.userName}"/>

<property name="password" value="${jdbc.password}"/>

</bean>-->

<!--002.使用c3p0数据源

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">

<property name="driverClass" value="${jdbc.driverClass}"/>

<property name="jdbcUrl" value="${jdbc.jdbcUrl}"/>

<property name="user" value="${jdbc.userName}"/>

<property name="password" value="${jdbc.password}"/>

</bean>-->

<!--003.使用dbcp数据源-->

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">

<property name="driverClassName" value="${jdbc.driverClass}"/>

<property name="url" value="${jdbc.jdbcUrl}"/>

<property name="username" value="${jdbc.userName}"/>

<property name="password" value="${jdbc.password}"/>

</bean>

<!--03.配置dao 在StudentDaoImpl里要使用数据源-->

<bean id="studentDaoImpl" class="cn.pb.dao.impl.StudentDaoImpl">

<property name="dataSource" ref="dataSource"/>

</bean>

<!--04.配置service-->

<bean id="studentServiceImpl" class="cn.pb.service.impl.StudentServiceImpl">

<property name="dao" ref="studentDaoImpl"/>

</bean>

</beans>

06.测试代码:

package cn.pb;

import cn.pb.bean.Student;

import cn.pb.service.StudentService;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

public class TestJdbc {

public static void main(String[] args) {

ApplicationContext context=new

ClassPathXmlApplicationContext("applicationContext.xml");

StudentService service= (StudentService) context.getBean("studentServiceImpl");

//service.addStudent(new Student(25,"xixi"));

List<Student> list=service.findAllStudents();

System.out.println(list);

}

}

本文内容总结:1.ORM框架的映射,01.JDBC连接数据库以前的方式代码,并给对象赋值,02.我们使用反射机制来 动态的给 Student对象赋值,2.Spring的JDBC:,01.实体类代码:,02.dao层代码:,03.service层代码:,04.连接数据库的properties文件:jdbc.properties,05.applicationContext.xml文件:,06.测试代码:,

原文链接:https://www.cnblogs.com/lyb0103/p/7658530.html

以上是 Spring笔记05(Spring JDBC三种数据源和ORM框架的映射) 的全部内容, 来源链接: utcz.com/z/362655.html

回到顶部