Database programming Spring light into the light - the loading force does not brag force

Database programming Spring light into the light - the loading force does not brag force

Foreword

  The instruments I wrote the core of Spring Inversion of Control and Dependency Injection, and later link up the notes, behind this supposed to write Spring AOP, but I think for starters, this part can first put up, first entry, and then look back at the core of understanding these I feel better, I do not know that's right, if understood properly, but also look exhibitions. Cipian for the Spring of database programming, mainly about jdbcTemplate, for beginners to get started directly. 

Database cut

  Database Programming is the foundation of the Internet programming, Spring JDBC framework provides a template model for developers, jdbcTemplate that is, it can simplify a lot of code, need to be reminded that jdbcTemplate not commonly used in practical applications, but I think for the novice fly again small is meat, in order to move forward, you have to eat the flesh of these small.

 

Spring JDBC configuration

Use Spring JDBC database operations, it needs to be configured with the following configuration

<! - Configure the jdbcTemplate-Spring -> 
<! - Configuration Data Source -> 
<the bean ID = "the dataSource" class = "org.springframework.jdbc.datasource.DriverManagerDataSource"> 
    <! - the MySQL database driver - -> 
    <Property name = "driverClassName" value = "com.mysql.jdbc.Driver"> </ Property> 
    <- the uRL of connection to the database ->! 
    <Property name = "url" value = "jdbc: MySQL: localhost //: 3306 / = bbb useUnicode to true & characterEncoding = UTF-8 "> </ Property>? 
    <- user name to connect the database ->! 
    <Property name =" username "value =" root "> </ Property> 
    <! - code connecting to the database -> 
    <Property name = "password" value = "the root"> </ Property> 
</ the bean>
<!--配置JDBC模板-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="dataSource"></property>
</bean>

 

  

DataSource configuration needs to be injected into the JDBC template to jdbcTemplate, and in the data access layer (Dao class) need to use jdbcTemplate also needs to be injected into the corresponding jdbc Template Bean, I demonstrate this with the most simple annotation injection

@Repository ( "userDao") 

public class UserDaoImpl the implements UserDao { 

    @Autowired 

    // template using JDBC profile 

    Private the JdbcTemplate the jdbcTemplate; 

}

  

 

Spring Jdbc Template common method

In the above we get the JDBC template, following me how to use it. First of all you need to know JdbcTemplate commonly used method, commonly used method is to update the class and query.

1public int update(String sql,Object args[])
The method may add, modify, or delete operation on the data table. Use args [] set the parameters in the SQL statement, and returns the number of rows updated.
Examples are as follows:
void the Add public () { 

    String INSERT SQL = "INSERT INTO User values (null,,??)"; 

    Object parem1 [] = { "success", "123456"}; 

    jdbcTemplate.update (INSERT SQL, parem1); 

    the System.out .println ( "add functionality in UserDao achieved"); 

}

  

 
2public List<T> query(String sql,RowMapper<T> rowMapper,Object args[])
The method may operate to query the data tables, rowMapper result set are mapped to user-defined class (if class is a custom attribute corresponding to the field data table).
 
Examples are as follows:
public void query() {

    String selectSql = "select * from user";

    RowMapper<User> rowMapper = new BeanPropertyRowMapper<User>(User.class);

    List<User> list = jdbcTemplate.query(selectSql,rowMapper,null);

    System.out.println("UserDao中的查询功能实现了");

}

   

Case aid

Pom.xml

<dependencies>

  <dependency>

    <groupId>junit</groupId>

    <artifactId>junit</artifactId>

    <version>4.11</version>

    <scope>test</scope>

  </dependency>

  <dependency>

    <groupId>javax.servlet</groupId>

    <artifactId>javax.servlet-api</artifactId>

    <version>3.1.0</version>

  </dependency>



  <dependency>

    <groupId>javax.servlet</groupId>

    <artifactId>jstl</artifactId>

    <version>1.2</version>

  </dependency>



  <dependency>

    <groupId>mysql</groupId>

    <artifactId>mysql-connector-java</artifactId>

    <version>5.1.38</version>

  </dependency>

  <!--spring核心依赖-->

  <dependency>

    <groupId>org.springframework</groupId>

    <artifactId>spring-core</artifactId>

    <version>5.1.5.RELEASE</version>

  </dependency>

  <dependency>

    <groupId>org.springframework</groupId>

    <artifactId>spring-beans</artifactId>

    <version>5.1.5.RELEASE</version>

  </dependency>

  <dependency>

    <groupId>org.springframework</groupId>

    <artifactId>spring-context</artifactId>

    <version>5.1.5.RELEASE</version>

  </dependency>

  <dependency>

    <groupId>org.springframework</groupId>

    <artifactId>spring-aop</artifactId>

    <version>5.1.5.RELEASE</version>

  </dependency>

  <dependency>

    <groupId>org.springframework</groupId>

    <artifactId>spring-jdbc</artifactId>

    <version>5.1.5.RELEASE</version>

  </dependency>

  <dependency>

    <groupId>org.springframework</groupId>

    <artifactId>spring-web</artifactId>

    <version>5.1.5.RELEASE</version>

  </dependency>

  <dependency>

    <groupId>org.springframework</groupId>

    <artifactId>spring-webmvc</artifactId>

    <version>5.1.5.RELEASE</version>

  </dependency>

  <dependency>

    <groupId>org.springframework</groupId>

    <artifactId>spring-expression</artifactId>

    <version>5.1.5.RELEASE</version>

  </dependency>

  <dependency>

    <groupId>org.springframework</groupId>

    <artifactId>spring-tx</artifactId>

    <version>5.1.5.RELEASE</version>

  </dependency>

  <!--日志相关-->

  <dependency>

    <groupId>commons-logging</groupId>

    <artifactId>commons-logging</artifactId>

    <version>1.2</version>

  </dependency>



</dependencies>
 

  

spring-config.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"

       xmlns:tx="http://www.springframework.org/schema/tx"

       xmlns:mvc="http://www.springframework.org/schema/mvc"

       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

       http://www.springframework.org/schema/tx

       http://www.springframework.org/schema/tx/spring-tx.xsd 

       http://www.springframework.org/schema/mvc 

       http://www.springframework.org/schema/mvc/spring-mvc. XSD 

        "> 

    ! <- annotations arranged to scan packages -> 

    <context: Component Base-package-scan =" com.my "> </ context: Component-scan> 

    <MVC: annotation-Driven> </ MVC : Annotation-Driven> 



    <- specified class TestDaoImpl configuration to Spring, Spring lets create an instance ->! 

    <bean the above mentioned id = "testDIDao" class = "com.my.dao.impl.TestDaoImpl" /> 

    <-! - use constructor injection -> 

    <-! <the bean ID = "testDIService" class = "com.my.service.impl.TestServiceImpl"> -> 

        <-! <!- The TestDIDao injected onto class attribute testDao TestDIServiceImpl -> -> 

        <-! <Constructor Arg-index = "0" = REF "testDIDao" /> ->

    <-! </ the bean> -> 

    <-! setter methods using injection -> 

    <the bean ID = "testDIService" class = "com.my.service.impl.TestServiceImpl"> 

        <-! class calls TestDIServiceImpl the setter method, the injected onto TestDao class attribute testDao TestServiceImpl -> 

        <property name = "the TestDAO" REF = "testDIDao"> </ property> 

    </ the bean> 



    <-! configure the jdbcTemplate-Spring -> 

    < ! - source configuration data -> 

    <the bean ID = "the dataSource" class = "org.springframework.jdbc.datasource.DriverManagerDataSource"> 

        <-! the MySQL database driver -> 

        <Property name = "driverClassName" value = " com.mysql.jdbc.Driver "> </ Property> 

        <-! the URL of connection to the database ->

        <property name="url" value="jdbc:mysql://localhost:3306/bbb?useUnicode=true&characterEncoding=UTF-8"></property>

        <! - username connection to the database -> 

        <Property name = "username" value = "root"> </ Property> 

        <! - password to connect to the database -> 

        <Property name = "password" value = " root "> </ Property> 

    </ bean> 

    <-! JDBC configuration templates -> 

    <bean the above mentioned id =" jdbcTemplate "class =" org.springframework.jdbc.core.JdbcTemplate "> 

        <Property name =" dataSource "ref = "dataSource"> </ Property> 

    </ bean> 

    <-! configuration Services -> 

    <bean the above mentioned id = "txManager" class = "org.springframework.jdbc.datasource.DataSourceTransactionManager"> 

        <Property name = "dataSource" ref = "dataSource "> </ Property> 

    </ bean> 

    <- Registration annotation-driven ->! 

    <tx: Transaction-Driven-Annotation Manager =" txManager "> </ tx: Annotation-Driven>

</beans>
 

  

User

package com.my.pojo;



public class User {

    private int id;

    private String username;

    private String password;



    public User() {

    }



    public User(int id, String username, String password) {

        this.id = id;

        this.username = username;

        this.password = password;

    }



    public int getId() {

        return id;

    }



    public void setId(int id) {

        this.id = id;

    }



    public String getUsername() {

        return username;

    }



    public void setUsername(String username) {

        this.username = username;

    }



    public String getPassword() {

        return password;

    }



    public void setPassword(String password) {

        this.password = password;

    }



    @Override

    public String toString() {

        return "User{" +

                "id=" + id +

                ", username='" + username + '\'' +

                ", password='" + password + '\'' +

                '}';

    }

}
 

  

UserDao

package com.my.dao;



public interface UserDao {

    public void add();

    public void delete();

    public void update();

    public void query();

}

  

 

UserDaoImpl

package com.my.dao.impl;



import com.my.dao.UserDao;

import com.my.pojo.User;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.jdbc.core.BeanPropertyRowMapper;

import org.springframework.jdbc.core.JdbcTemplate;

import org.springframework.jdbc.core.RowMapper;

import org.springframework.stereotype.Repository;



import java.util.List;



@Repository("userDao")

public class UserDaoImpl implements UserDao {

    @Autowired

    //使用配置文件中的JDBC模板

   private JdbcTemplate jdbcTemplate;



    @Override

    public void add() {

        String insertSql = "insert into user values(null,?,?)";

        for (int I = 0; I <15; I ++) { 

            Object parem1 [] = { "success", "123456"}; 

            jdbcTemplate.update (INSERT SQL, parem1); 

        } 

        System.out.println (added in UserDao " function achieved "); 

    } 



    @Override 

    public void Delete () { 

        String deleteSql =" Delete User from WHERE ID = ";? 

        Object parem2 [] = {}. 5; 

        jdbcTemplate.update (deleteSql, parem2); 

        the System.out. println ( "deletion function is achieved UserDao"); 

    } 



    @Override 

    public void Update () { 

        String updateSQL = "Update User SET = username, password = WHERE ID =???"; 

        Object parem3 [] = { "Review ""654321",3};

        jdbcTemplate.update (updateSQL, parem3); 

        System.out.println ( "editing in UserDao achieved"); 

    } 



    @Override 

    public void Query () { 

        String selectSql = "SELECT * from User"; 

        the RowMapper <the User> rowMapper new new BeanPropertyRowMapper = <the User> (User.class); 

        List <the User> List = jdbcTemplate.query (selectSql, rowMapper, null); 

        System.out.println ( "search function in UserDao achieved"); 

        for (the User User : List) { 

            System.out.println (User); 

        } 

    } 

}

  


Test Test3

package com.my.test;



import com.my.dao.UserDao;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;



public class Test3 {

    @Autowired

    private  UserDao userDao;

    

    public static void main(String[] args) {



       ApplicationContext appCon = new ClassPathXmlApplicationContext("spring-config.xml");

        //从容器中获取目标对象

        UserDao userDao = (UserDao) appCon.getBean("userDao");



        //userDao.add();

        userDao.delete();

        userDao.update();

        userDao.query();

    }

}

  

 

Test Results

 

 

 

 

End

对于Spring JbdcTemplate的讲解到此结束,对于新手来说没必要太复杂,能完成增删改查做个入门即可,等了解了再详细学习才有帮助,希望能对一些需要的朋友有用吧。

 

相关链接

Spring浅入浅出https://www.cnblogs.com/zyx110/p/11306998.html

Spring注解浅入浅出https://www.cnblogs.com/zyx110/p/11310139.html

没有无缘无故的编程https://www.cnblogs.com/zyx110/p/11297822.html

自定义框架https://www.cnblogs.com/zyx110/p/11295044.html

Spring框架知多少https://www.cnblogs.com/zyx110/p/11022891.html

用IDEA开发Spring程序https://www.cnblogs.com/zyx110/p/11023218.html

 

欲知下文如何,请看下回讲解。

 

 

*****************************************************************************************************

我的博客园地址:https://www.cnblogs.com/zyx110/

转载请说明出处

我不能保证我所说的都是对的,但我能保证每一篇都是用心去写的,我始终认同“分享的越多,你的价值增值越大”,欢迎大家关注我的技术分享“Java匹马行天下”和学习心得分享“匹马行天下”,在分享中进步,越努力越幸运,人生赢在转折处,改变从现在开始!

支持我的朋友们记得点波推荐哦,您的肯定就是我前进的动力。

 

Guess you like

Origin www.cnblogs.com/zyx110/p/11314839.html