Spring's jdbcTemplate uses study notes to simplify our operations on the database

    I said before that the spring framework has solutions for each layer, and also provides solutions for the persistence layer: ORM modules and JDBC templates. Next, let's first understand the simple use of the JDBC template through a small case.
    Preparation: Because the persistence layer operates on the database, we need to create a database table first, and we can create a database table at will. What I created is the account data table:

CREATE TABLE `account` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
  `name` varchar(255) NOT NULL COMMENT '用户名',
  `money` float NOT NULL COMMENT '金额',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;

Create a maven project and add the following coordinates in the pom file:

 <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.8.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.2.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
 </dependencies>

Create a package in the maven project according to your own habits, create a class, and write a main function. What I wrote is as follows:

public class JdbcTemplateDemo {
    
    
    public static void main(String[] args) {
    
    
        //创建数据源
        DriverManagerDataSource dm = new DriverManagerDataSource();
        //设置数据库连接信息
        dm.setDriverClassName("com.mysql.jdbc.Driver");
        dm.setUrl("jdbc:mysql://localhost:3306/stu");
        dm.setUsername("root");
        dm.setPassword("123456");
        //创建JdbcTemplate对象
        JdbcTemplate jt = new JdbcTemplate(dm);
        //执行sql语句
        jt.update("insert into account(name,money) value (?,?)","小八","1000");
        //jt.execute("insert into account(name,money) value ('小五',1000)");
    }
}

    The result of the execution is to add a piece of data to the database we created. The above is the simple use of the JDBC template in spring. The above code is still problematic. Now that we have learned the springIoc container, we have found that the creation of the data source and the creation of the JdbcTemplate template are all through new, and the database connection information is set through the set method. These can all be set through springIoc. Container to solve. Next, I modify the above code.
    Create a bean.xml file and configure it as follows:

<?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">

    <!--配置数据源,我在这使用的是spring框架中的内置的数据源,其实也可以使用c3p0,dbcp,durid数据库连接池-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/stu"></property>
        <property name="username" value="root"></property>
        <property name="password" value="123456"></property>
    </bean>

    <!--配置jdbcTemplate模板-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <constructor-arg name="dataSource" ref="dataSource"></constructor-arg>
    </bean>
</beans>

Let's write another main method:

public class JdbcTemplateDemo2 {
    
    
    public static void main(String[] args) {
    
    
        //加载bean.xml文件
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        //获取jdbcTemplate模板的bean对象
        JdbcTemplate jt = (JdbcTemplate) context.getBean("jdbcTemplate");
        //执行sql语句
        jt.update("insert into account(name,money) value (?,?)", "小九", "1000");
    }
}

    The above is the code after our transformation. Next, I will use JdbcTemplate to write a few methods in dao to run and see the results.
Account entity class:

public class Account implements Serializable {
    
    
    private Integer id;
    private String name;
    private Float money;
    //get/set方法别忘记生成
    //toString方法也别忘记生成
}

AccountDao interface:

public interface AccountDao {
    
    
    /**
    * 查询所有用户
    */
    List<Account> findAll();

    /**
     * 根据id查询用户
     */
    Account findAccountById(Integer accountId);

    /**
     * 根据用户名查询用户
     */
    Account findAccountByName(String accountName);

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

    /**
     * 删除账户
     */
    void deleteAccountById(Integer accountId);
}

AccountDaoImpl interface implementation class:

public class AccountDaoImpl implements AccountDao {
    
    

    private JdbcTemplate jdbcTemplate;

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

    public List<Account> findAll() {
    
    
        List<Account> list = jdbcTemplate.query("select * from account",new BeanPropertyRowMapper<Account>(Account.class));
        return list;
    }

    public Account findAccountById(Integer accountId) {
    
    
        List<Account> list = jdbcTemplate.query("select * from account where id = ?",new BeanPropertyRowMapper<Account>(Account.class),accountId);
        return list.isEmpty() ? null : list.get(0);
    }

    public Account findAccountByName(String accountName) {
    
    
        List<Account> list = jdbcTemplate.query("select * from account where name = ?", new BeanPropertyRowMapper<Account>(Account.class), accountName);
        if (list.isEmpty()){
    
    
            return null;
        }else if (list.size() > 1){
    
    
            throw new RuntimeException("结果集不唯一");
        }
        return list.get(0);
    }

    public void updateAccount(Account account) {
    
    
        jdbcTemplate.update("update account set name = ? , money = ? where id = ?", account.getName(),account.getMoney(),account.getId());

    }

    public void deleteAccountById(Integer accountId) {
    
    
        jdbcTemplate.update("delete from account where id = ?" , accountId);
    }
}

Run the main method to see the result:

public class JdbcTemplateDemo3 {
    
    
    public static void main(String[] args) {
    
    
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        AccountDao jt = (AccountDao) context.getBean("accountDao");
        //查询所用账户信息
        List<Account> lists = jt.findAll();
        for (Account list : lists){
    
    
            System.out.println(list);
        }
    }
}

Query result:
Insert picture description here
query an account according to id:

Account account = jt.findAccountById(4);
System.out.println(account);

Operation result:
Insert picture description here
I won't demonstrate the other methods, if you don't understand, you can leave a message for me.
There are these lines of code in the AccountDaoImpl implementation class. It is more troublesome to write the following code for different persistence layers:

private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
    this.jdbcTemplate = jdbcTemplate;
}
//可以通过继承JdbcDaoSupport类来解决这个问题
public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao {
    
    

    /*private JdbcTemplate jdbcTemplate;

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

    public List<Account> findAll() {
    
    
        List<Account> list = super.getJdbcTemplate().query("select * from account",new BeanPropertyRowMapper<Account>(Account.class));
        return list;
    }
    //其他几个方法我就不写了,也就改了super.getJdbcTemplate()这个代码
}

    What is the specific difference between inheriting JdbcDaoSupport and writing JdbcTemplate in dao? The difference is that we can't develop through annotations if we inherit, because these codes cannot be modified in the spring framework, and we can only use the xml method. In the way of defining JdbcTemplate in dao, both xml and annotation methods can be used.
    Of course, we only use the xml method here, and the annotation method is also possible. We need to enable annotation scanning in bean.xml

<!--开启注解扫描-->
<context:component-scan base-package="com.zy.jdbcTemplate.dao"></context:component-scan>

Modify the AccountDaoImpl implementation class and add annotations:

@Repository("accountDao")
public class AccountDaoImpl /*extends JdbcDaoSupport*/ implements AccountDao {
    
    

    @Autowired
    private JdbcTemplate jdbcTemplate;
    //......
}

Come on! ! !

Guess you like

Origin blog.csdn.net/qq_42494654/article/details/113871643