【JAVA】Srping和传统JDBC实现数据库操作

前言

学习完了【JAVA】Spring对JDBC的支持【JAVA】JAVA数据源之后,那我们就可以进行数据库的操作了。

创建数据库

首先创建我们的数据库(这里我使用的是Mysql),为了演示方便,我这里简单的创建一个spring数据库,然后数据库有一个user用户表:

  1. 创建一个名为spring的数据库。
  2. 创建一个名为user的数据表,表包括id、email、name、password四个字段。
CREATE TABLE `user` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `email` varchar(255) DEFAULT NULL,
  `name` varchar(255) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=latin1;

在这里插入图片描述

创建实体类

创建一个实体类和数据库的表相对应(模型用来储存要操作的数据)。

package cn.zhenta.www.service.impl.Entity;

public class User {
    int id;
    String email;
    String name;
    String password;

    public User(String email, String name, String password){
        this.email = email;
        this.name = name;
        this.password = password;
    }

    public int getId(){
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getEmail(){
        return email;
    }

    public void setEmail(String email){
        this.email = email;
    }

    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;
    }
}

在这里插入图片描述
模型中的成员属性idemailnamepassword分别对应数据表user的字段,为每个成员属性添加gettersetter方法,实现对成员属性的操作。

数据访问对象(DAO)模式

DAO(data access object),数据库访问对象,主要的功能就是用于惊险数据库操作的。

UserDao接口

package cn.zhenta.www.service.impl.Dao;

import cn.zhenta.www.service.impl.Entity.User;

public interface UserDao {
    public void inSert(User User);
}

在这里插入图片描述
抽象了User的操作,即User可以进行插入操作(inSert)

UserDao接口的实现

package cn.zhenta.www.service.impl.Dao.impl;

import cn.zhenta.www.service.impl.Dao.UserDao;
import cn.zhenta.www.service.impl.Entity.User;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class UserDaoImpl implements UserDao {
    private DataSource dataSource;

    public void setDataSource(DataSource dataSource){
        this.dataSource = dataSource;
    }

    public void inSert(User user){
        String sql = "INSERT INTO `spring`.`user` (`email`, `name`, `password`) VALUES (?, ?,?)";
        Connection conn = null;

        try{
            conn = dataSource.getConnection();
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, user.getEmail());
            ps.setString(2, user.getName());
            ps.setString(3, user.getPassword());
            ps.executeUpdate();
            ps.close();
        }catch(SQLException e){
            throw new RuntimeException(e);
        }finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {}
            }
        }
    }
}

在这里插入图片描述
这里直接用了传统的JDBC,没有使用Spring的JdbcTemplate或者别的ORM框架。传统JDBC和Spring的JdbcTemplate区别
private DataSource dataSource;这里对

数据源配置

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

    <bean id="customerDAO" class="cn.zhenta.www.service.impl.Dao.impl.UserDaoImpl">
        <property name="dataSource" ref="dataSource" />
    </bean>

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

        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/spring" />
        <property name="username" value="root" />
        <property name="password" value="root" />
    </bean>

</beans>

在这里插入图片描述
这里为了方便直接使用了直连的数据源关于直连的数据源和连接池的数据源),也可以使用连接池的数据源。

    <bean id="customerDAO" class="cn.zhenta.www.service.impl.Dao.impl.UserDaoImpl">
        <property name="dataSource" ref="dataSource" />
    </bean>

其中name="dataSource"为向cn.zhenta.www.service.impl.Dao.impl.UserDaoImpl这个类名为dataSource成员属性注入一个iddataSourceref="dataSource")的Bean(通过setter方法即setDataSource),也就是

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

        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/spring" />
        <property name="username" value="root" />
        <property name="password" value="root" />
    </bean>

这样在UserDao的实现类UserDaoImpl就能完成了数据源的装配了。

装配Bean

package cn.zhenta.www.service.impl.Config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;

@Configuration
@ImportResource(locations = {"Spring-Datasource.xml"})
@ComponentScan(basePackages = {"cn.zhenta.www.service.impl"})
public class Config {
}

在这里插入图片描述

@Configuration声明这个是配置类,@ImportResource装配xml配置文件(Spring-Datasource.xml为直连数据源的配置文件),@ComponentScan开启组件扫描。

测试类

package cn.zhenta.www.service.impl.TestC;

import cn.zhenta.www.service.impl.Dao.UserDao;
import cn.zhenta.www.service.impl.Entity.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;

@ContextConfiguration(classes = cn.zhenta.www.service.impl.Config.Config.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class TestC {

    @Autowired
    UserDao userDao;

    @Test
    public void dd(){
        User user = new User("22", "xue8","22");
        userDao.inSert(user);
    }
}

在这里插入图片描述

ContextConfiguration 指定Spring配置信息来源,UserDao userDAO引用UserDao接口,User user = new User("22", "xue8","22")创建一个User实体类中储存我们要保存的数据,userDAO.inSert(user)通过接口的实现类插入数据。接口的引用

最后我们数据库成功插入了我们插入的数据。
在这里插入图片描述

欢迎加入JAVA学习群949419296,一起交流!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值