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

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