Spring基于XML的数据库CRUD操作以及基于注解的方式

方式一:基于XML的数据库CRUD操作
持久层技术选择 dbutiils
poml.xml中的依赖有:

<dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.16</version>
        </dependency>
        <dependency>
            <groupId>commons-dbutils</groupId>
            <artifactId>commons-dbutils</artifactId>
            <version>1.4</version>
        </dependency>
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>
    </dependencies>

1.目录结构

目录结构

2.代码部分:

1.数据库的实体类Account.java

public class Account implements Serializable {
    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 +
                '}';
    }
}

2.业务层代码:

  • IAccountService接口
public interface IAccountService {
    /**
     * 查询所有
     * @return
     */
    List<Account> findAllAccount();

    /**
     * 查询一个
     * @return
     */
    Account findById(Integer accountId);

    /**
     * 插入数据
     * @param account
     */
    void saveAccount(Account account);

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

    /**
     * 删除
     * @param accountId
     */
    void deleteAccount(Integer accountId);
}

  • AccountServiceImpl.java
public class AccountServiceImpl implements IAccountService {
    private IAccountDao accountDao;

    public void setAccountDao(IAccountDao accountDao) {
        this.accountDao = accountDao;
    }

    public List<Account> findAllAccount() {
        return accountDao.findAllAccount();
    }

    public Account findById(Integer accountId) {
        return accountDao.findById(accountId);
    }

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

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

    public void deleteAccount(Integer accountId) {
        accountDao.deleteAccount(accountId);
    }
}

3.持久层代码

  • IAccountDao接口
/**
 * 账户的持久层接口
 */
public interface IAccountDao {
    /**
     * 查询所有
     * @return
     */
    List<Account> findAllAccount();

    /**
     * 查询一个
     * @return
     */
    Account findById(Integer accountId);

    /**
     * 插入数据
     * @param account
     */
    void saveAccount(Account account);

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

    /**
     * 删除
     * @param accountId
     */
    void deleteAccount(Integer accountId);
}

  • AccountDaoImpl.java
public class AccountDaoImpl implements IAccountDao {
    private QueryRunner runner;

    public void setRunner(QueryRunner runner) {
        this.runner = runner;
    }

    public List<Account> findAllAccount() {
        try {
            return runner.query("select * from account",new BeanListHandler<Account>(Account.class));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

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

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

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

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

4.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="accountService"   class="com.xatu.service.impl.AccountServiceImpl">
        <!--注入dao -->
        <property name="accountDao" ref="accountDao"></property>
    </bean>
    <bean id="accountDao" class="com.xatu.dao.impl.AccountDaoImpl">
        <property name="runner" ref="runner"></property>
    </bean>
    <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
        <!--注入数据源 -->
        <constructor-arg name="ds" ref="dataSource"></constructor-arg>
    </bean>

    <!--配置数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!--连接数据库的必备信息 -->
        <property name="driverClass" value="com.mysql.cj.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql:///day15?charactarEncoding=UTF-8&amp;useSSL=false&amp;serverTimezone=Asia/Shanghai"></property>
        <property name="user" value="root"></property>
        <property name="password" value="root"></property>
    </bean>
</beans>

5.测试类

/**
 * 使用Junit进行单元测试,测试配置
 */
public class AccountServiceTest {

    @Test
    public void testFindAll(){
        //获取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.得到业务层对象
        IAccountService as= (IAccountService) ac.getBean("accountService");
        List<Account> accounts = as.findAllAccount();
        for (Account account:
             accounts) {
            System.out.println(account);
        }
    }
    @Test
    public void testFindOne(){
        //获取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.得到业务层对象
        IAccountService as= (IAccountService) ac.getBean("accountService");
        Account account = as.findById(2);
        System.out.println(account);
    }
    @Test
    public void testSave(){
        Account account=new Account();
        //获取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.得到业务层对象
        IAccountService as= (IAccountService) ac.getBean("accountService");
        account.setName("ddd");
        account.setMoney(1000);
        as.saveAccount(account);
    }
    @Test
    public void testUpdate(){
        //获取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.得到业务层对象
        IAccountService as= (IAccountService) ac.getBean("accountService");
        Account account1 = as.findById(4);
        account1.setMoney(2000);
        as.updateAccount(account1);
    }
    @Test
    public void testDelete(){
        //获取容器
        ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
        //2.得到业务层对象
        IAccountService as= (IAccountService) ac.getBean("accountService");
        as.deleteAccount(4);
    }
}

第二种方式:基于注解的数据库CRUD操作

1.目录结构

目录结构2

2.代码部分

数据库的实体类Account.java

public class Account implements Serializable {
    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 +
                '}';
    }
}

2.业务层代码

  • IAccountService接口
public interface IAccountService {
    /**
     * 查询所有
     * @return
     */
    List<Account> findAllAccount();

    /**
     * 查询一个
     * @return
     */
    Account findById(Integer accountId);

    /**
     * 插入数据
     * @param account
     */
    void saveAccount(Account account);

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

    /**
     * 删除
     * @param accountId
     */
    void deleteAccount(Integer accountId);
}

  • AccountServiceImpl.java
@Service("accountService")   //将当前类对象存入spring容器中
public class AccountServiceImpl implements IAccountService {
    @Autowired   //注入数据
    private IAccountDao accountDao;

    public List<Account> findAllAccount() {
        return accountDao.findAllAccount();
    }

    public Account findById(Integer accountId) {
        return accountDao.findById(accountId);
    }

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

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

    public void deleteAccount(Integer accountId) {
        accountDao.deleteAccount(accountId);
    }
}

3.持久层代码

  • IAccountDao接口
/**
 * 账户的持久层接口
 */
public interface IAccountDao {
    /**
     * 查询所有
     * @return
     */
    List<Account> findAllAccount();

    /**
     * 查询一个
     * @return
     */
    Account findById(Integer accountId);

    /**
     * 插入数据
     * @param account
     */
    void saveAccount(Account account);

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

    /**
     * 删除
     * @param accountId
     */
    void deleteAccount(Integer accountId);
}

  • AccountDaoImpl.java
@Repository("accountDao")   //将当前类对象存入spring容器中
public class AccountDaoImpl implements IAccountDao {
    @Autowired   //为runner注入数据
    private QueryRunner runner;


    public List<Account> findAllAccount() {
        try {
            return runner.query("select * from account",new BeanListHandler<Account>(Account.class));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

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

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

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

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

4.配置类

  • springConfiguration.java
@Configuration    //声明这是配置类
@ComponentScan(basePackages = "com.xatu")   //告知spring容器在创建容器时要扫描的包
@PropertySource("classpath:jdbcUtil.properties")  //指定properties文件的位置
public class springConfiguration {
    @Value("${jdbc.driver}")    //为普通类型变量注入数据
    private String jdbcDriver;
    @Value("${jdbc.url}")
    private String jdbcurl;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

    @Bean("runner")  //将创建的QueryRunner对象存入spring容器中
    @Scope("prototype")    //指定bean的作用范围为多例
    public QueryRunner createQueryRunner(DataSource dataSource){
        return new QueryRunner(dataSource);
    }

    @Bean("dataSource")   //将创建的dataSource对象存入spring容器中
    public DataSource createDataSource(){
        try {
            ComboPooledDataSource ds = new ComboPooledDataSource();
            ds.setDriverClass(jdbcDriver);
            ds.setJdbcUrl(jdbcurl);
            ds.setUser(username);
            ds.setPassword(password);
            return ds;
        }catch (Exception e){
            throw new RuntimeException();
        }
    }
}

  • 数据库配置jdbcUtil.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql:///day15?charactarEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai
jdbc.username=root
jdbc.password=root

5.测试类

  • AccountServiceTest.java
public class AccountServiceTest {

    @Test
    public void testFindAll(){
        //获取容器
        ApplicationContext ac = new AnnotationConfigApplicationContext(springConfiguration.class);
        //2.得到业务层对象
        IAccountService as= (IAccountService) ac.getBean("accountService");
        List<Account> accounts = as.findAllAccount();
        for (Account account:
             accounts) {
            System.out.println(account);
        }
    }
    @Test
    public void testFindOne(){
        //获取容器
        ApplicationContext ac = new AnnotationConfigApplicationContext(springConfiguration.class);
        //2.得到业务层对象
        IAccountService as= (IAccountService) ac.getBean("accountService");
        Account account = as.findById(2);
        System.out.println(account);
    }
    @Test
    public void testSave(){
        Account account=new Account();
        //获取容器
        ApplicationContext ac = AnnotationConfigApplicationContext(springConfiguration.class);
        //2.得到业务层对象
        IAccountService as= (IAccountService) ac.getBean("accountService");
        account.setName("ddd");
        account.setMoney(1000);
        as.saveAccount(account);
    }
    @Test
    public void testUpdate(){
        //获取容器
        ApplicationContext ac = AnnotationConfigApplicationContext(springConfiguration.class);
        //2.得到业务层对象
        IAccountService as= (IAccountService) ac.getBean("accountService");
        Account account1 = as.findById(4);
        account1.setMoney(2000);
        as.updateAccount(account1);
    }
    @Test
    public void testDelete(){
        //获取容器
        ApplicationContext ac = new AnnotationConfigApplicationContext(springConfiguration.class);
        //2.得到业务层对象
        IAccountService as= (IAccountService) ac.getBean("accountService");
        as.deleteAccount(4);
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章