Spring快速入门实例:基于纯注解的CRUD

我们的项目是Maven工程,项目结构如下:

Spring快速入门实例:基于纯注解的CRUD_第1张图片

pom.xml:



    4.0.0

    com.zl
    spring_day02_example_crud_anno
    1.0-SNAPSHOT

    
        
            
                org.apache.maven.plugins
                maven-compiler-plugin
                
                    8
                    8
                
            
        
    
    jar

    
        
            org.springframework
            spring-context
            5.0.2.RELEASE
        

        
            org.springframework
            spring-test
            5.0.2.RELEASE
        

        
            mysql
            mysql-connector-java
            5.1.6
        

        
            junit
            junit
            4.12
        

        
            c3p0
            c3p0
            0.9.1.2
        

        
            commons-dbutils
            commons-dbutils
            1.4
        

    

com.zl.domain.Account实体类:

package com.zl.domain;

public class Account {

    private Integer id;
    private String name;
    private Float money;

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Float getMoney() {
        return money;
    }

    public void setMoney(Float money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }
}

com.zl.service.AccountService接口:

package com.zl.service;

import com.zl.domain.Account;

import java.util.List;

public interface AccountService {

    /**
     * 查找所有账户
     * @return
     */
    List findAll();

    /**
     * 根据id查询账户
     * @param id
     * @return
     */
    Account findById(Integer id);

    /**
     * 保存账户
     * @param account
     */
    void saveAccount(Account account);

    /**
     * 更新账户
     * @param account
     */
    void updateAccount(Account account);

    /**
     * 根据id删除用户
     * @param id
     */
    void deleteAccount(Integer id);
}

com.zl.service.AccountServiceImpl实现类:

package com.zl.service.impl;

import com.zl.dao.AccountDao;
import com.zl.domain.Account;
import com.zl.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("accountService")
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDao dao;

    public void setDao(AccountDao dao) {
        this.dao = dao;
    }

    public List findAll() {
        return dao.findAll();
    }

    public Account findById(Integer id) {
        return dao.findById(id);
    }

    public void saveAccount(Account account) {
        dao.saveAccount(account);
    }

    public void updateAccount(Account account) {
        dao.updateAccount(account);
    }

    public void deleteAccount(Integer id) {
        dao.deleteAccount(id);
    }
}

com.zl.dao.AccountDao接口:

package com.zl.dao;

import com.zl.domain.Account;

import java.util.List;

public interface AccountDao {
    /**
     * 查找所有账户
     * @return
     */
    List findAll();

    /**
     * 根据id查询账户
     * @param id
     * @return
     */
    Account findById(Integer id);

    /**
     * 保存账户
     * @param account
     */
    void saveAccount(Account account);

    /**
     * 更新账户
     * @param account
     */
    void updateAccount(Account account);

    /**
     * 根据id删除用户
     * @param id
     */
    void deleteAccount(Integer id);
}

com.zl.dao.AccountDaoImpl实现类:

package com.zl.dao.impl;

import com.zl.dao.AccountDao;
import com.zl.domain.Account;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;
import java.util.List;

@Repository("accountDao")
public class AccountDaoImpl implements AccountDao {

    @Autowired
    private QueryRunner queryRunner;

    public List findAll() {
        try {
            return queryRunner.query("select * from account",new BeanListHandler(Account.class));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public Account findById(Integer id) {
        try {
            return queryRunner.query("select * from account where id=?",new BeanHandler(Account.class),id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public void saveAccount(Account account) {
        try {
            queryRunner.update("insert into account(name,money) values(?,?)",account.getName(),account.getMoney());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public void updateAccount(Account account) {
        try {
            queryRunner.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public void deleteAccount(Integer id) {
        try {
            queryRunner.update("delete from account where id=?",id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

com.zl.conf.SpringConfiguration父配置类:

package com.zl.conf;

import org.springframework.context.annotation.*;

@Configuration
@ComponentScan("com.zl")
@PropertySource("classpath:jdbc.properties")
@Import(JdbcConfiguration.class)
public class SpringConfiguration {

}

com.zl.conf.JdbcConfiguration子配置类---数据库配置:

package com.zl.conf;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;

import javax.sql.DataSource;

//@Configuration
public class JdbcConfiguration {

    @Value("${jdbc.driver}")
    private String driver;

    @Value("${jdbc.url}")
    private String url;

    @Value("${jdbc.username}")
    private String username;

    @Value("${jdbc.password}")
    private String password;

    @Bean(name="runner")
    @Scope("prototype")
    public QueryRunner createQueryRunner(@Qualifier("ds1") DataSource dataSource){
        return new QueryRunner(dataSource);
    }

    @Bean(name="ds1")
    public DataSource createDataSource(){
        try {
            ComboPooledDataSource ds = new ComboPooledDataSource();
            ds.setDriverClass(driver);
            ds.setJdbcUrl(url);
            ds.setUser(username);
            ds.setPassword(password);
            return ds;
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    @Bean(name="ds2")
    public DataSource createDataSource2(){
        try {
            ComboPooledDataSource ds = new ComboPooledDataSource();
            ds.setDriverClass(driver);
            ds.setJdbcUrl(url);
            ds.setUser(username);
            ds.setPassword(password);
            return ds;
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }
}

resources资源根目录下的jdbc.properties:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring
jdbc.username=root
jdbc.password=root

测试类TestCRUD:

import com.zl.conf.SpringConfiguration;
import com.zl.domain.Account;
import com.zl.service.AccountService;
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(classes = SpringConfiguration.class)
public class TestCRUD {

    @Autowired
    private AccountService service;

    @Test
    public void testFindAll(){
        List accounts = service.findAll();
        accounts.stream().forEach(System.out::println);
    }

    @Test
    public void testFindById() {
        Account account = service.findById(2);
        System.out.println(account);
    }

    @Test
    public void testSaveAaccount() {
        Account account = new Account();
        account.setName("zhangsan");
        account.setMoney(5000f);
        service.saveAccount(account);
    }

    @Test
    public void testUpdateAccount() {
        Account account = new Account();
        account.setId(2);
        account.setMoney(5000f);
        account.setName("LR");
        service.updateAccount(account);
    }

    @Test
    public void testDeleteAccount() {
        service.deleteAccount(4);
    }
}

数据库:

create table account(
    id int primary key auto_increment,
    name varchar(40),
    money float
)character set utf8 collate utf8_general_ci;

insert into account(name,money) values('aaa',1000);
insert into account(name,money) values('bbb',1000);
insert into account(name,money) values('ccc',1000);

你可能感兴趣的:(Spring快速入门实例:基于纯注解的CRUD)