1. 程式人生 > >JAVA程式設計116——Spring : xml + jdbcTemplate 完成 CRUD

JAVA程式設計116——Spring : xml + jdbcTemplate 完成 CRUD

一、目錄結構

在這裡插入圖片描述

二、程式碼詳解

1、xml.配置檔案:bean.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"
       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"
>
<!--獲取資料來源配置檔案--> <context:property-placeholder location="classpath:db.properties"/> <!--載入資料來源--> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="${jdbc.driverClass}"
/>
<property name="JdbcUrl" value="${jdbc.jdbcUrl}"/> <property name="user" value="${jdbc.user}"/> <property name="password" value="${jdbc.password}"/> </bean> <!--建立JdbcTemplate--> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"
>
<!--新增dataSource依賴/構造方法依賴注入--> <constructor-arg name="dataSource" ref="dataSource"></constructor-arg> </bean> <!--建立userService--> <bean id="userService" class="com.mollen.service.impl.UserServiceImpl"> <!--新增userDao依賴/seteter依賴注入--> <property name="userDao" ref="userDao"></property> </bean> <!--建立userDao--> <bean id="userDao" class="com.mollen.dao.impl.UserDaoImpl"> <!--新增jdbcTemplate依賴--> <property name="jdbcTemplate" ref="jdbcTemplate"></property> </bean> </beans>
2、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>com.mollen</groupId>
    <artifactId>spring_exam</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.7.0</version>
                <configuration>
                    <target>1.8</target>
                    <source>1.8</source>
                </configuration>
            </plugin>
        </plugins>
    </build>
    
</project>
3、資料庫表:user

在這裡插入圖片描述

4、資料來源配置:db.properties
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/mybatis_day01
jdbc.user=root
jdbc.password=root
5、service層:

1、Userservice.java

package com.mollen.service;

import com.mollen.bean.User;

import java.util.Date;
import java.util.List;

/**
 * @ClassName: UserService
 * @Auther: Mollen
 * @CreateTime: 2018-11-03  19:40:55
 * @Description:
 */
public interface UserService {

    /**
     * 1.新增/更新使用者
     */
    public void addOrSaveUser(User user);

    /**
     * 2.刪除使用者
     */
    public void removeUser(Integer id);

    /**
     * 3.根據id查詢使用者
     */
    public User findById(Integer id);

    /**
     * 4.查詢所有使用者
     */
    public List<User> findAll();
}

2、UserserviceImpl.java

package com.mollen.service.impl;

import com.mollen.bean.User;
import com.mollen.dao.UserDao;
import com.mollen.service.UserService;

import java.util.List;

/**
 * @ClassName: UserServiceImpl
 * @Auther: Mollen
 * @CreateTime: 2018-11-03  19:41:22
 * @Description:
 */
public class UserServiceImpl  implements UserService{

    private UserDao userDao;

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public void addOrSaveUser(User user) {
        userDao.addOrSaveUser(user);
    }

    @Override
    public void removeUser(Integer id) {
        userDao.removeUser(id);
    }

    @Override
    public User findById(Integer id) {
        return userDao.findById(id);
    }

    @Override
    public List<User> findAll() {
        return userDao.findAll();
    }

}
6、dao層:

1、UserDao.java

package com.mollen.dao;

import com.mollen.bean.User;

import java.util.List;

/**
 * @ClassName: UserDao
 * @Auther: Mollen
 * @CreateTime: 2018-11-03  19:40:36
 * @Description:
 */
public interface UserDao {

    /**
     * 1.新增/更新使用者
     */
    public void addOrSaveUser(User user);

    /**
     * 2.刪除使用者
     */
    public void removeUser(Integer id);

    /**
     * 3.根據id查詢使用者
     */
    public User findById(Integer id);

    /**
     * 4.全查使用者
     */
    public List<User> findAll();

}

2、UserDaoImpl.java

package com.mollen.dao.impl;

import com.mollen.bean.User;
import com.mollen.dao.UserDao;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

/**
 * @ClassName:  UserDaoImpl
 * @Auther:     Mollen
 * @CreateTime: 2018-11-03  19:41:46
 * @Description:
 */
public class UserDaoImpl implements UserDao {

    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public void addOrSaveUser(User user) {
        jdbcTemplate.update("INSERT INTO user VALUES (null,?,?,?,?)",user.getUsername(),user.getBirthday(),user.getSex(),user.getAddress());

    }

    @Override
    public void removeUser(Integer id) {
        jdbcTemplate.update("DELETE  FROM  user  where id = ?",id);
    }

    @Override
    public User findById(Integer id) {
        try {
            return jdbcTemplate.queryForObject("SELECT * FROM user WHERE id = ?",new BeanPropertyRowMapper<User>(User.class), id);
        }catch (Exception e){
            e.printStackTrace();
            return  null;
        }
    }

    @Override
    public List<User> findAll() {
        return  jdbcTemplate.query("select * from user",new BeanPropertyRowMapper<User>(User.class));
    }
}
7、測試類:Test.java
package com.mollen.test;

import com.mollen.bean.User;
import com.mollen.service.UserService;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @ClassName: test
 * @Auther: Mollen
 * @CreateTime: 2018-11-05  10:17:54
 * @Description:
 */
public class MyTest {

    private  UserService userService;

    @Before
    public void init(){
        //建立web容器
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");
        //獲取業務層bean物件
        userService = (UserService) applicationContext.getBean("userService");
    }

    @Test
    public void test01(){
        List<User> users = userService.findAll();
        for (User user : users) {
            System.out.println(user);
        }
    }

    @Test
    public void test02(){
        User user = userService.findById(41);
        System.out.println(user);
    }

    @Test
    public void test03(){
        userService.removeUser(49);
    }

    @Test
    public void test04() throws ParseException {
        Date birthday = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2018-02-27 17:47:08");
        User user = new User();

        user.setUsername("里斯");
        user.setBirthday(birthday);
        user.setSex("男");
        user.setAddress("杭州");

        userService.addOrSaveUser(user);
    }

    @After
    public void destory(){

    }
}