2017-04-03 86 views
0

我正在訓練自己在Spring JDBC上,我正在學習本教程:Spring JDBC ExampleSpring JDBC使用application.properties文件

該教程是非常好的,執行代碼,我沒有問題。

爲了簡單和方便,我在這裏引用代碼。

頭等艙,學生(以db爲存儲實體):

package com.tutorialspoint; 

public class Student 
{ 
     private Integer age; 
     private String name; 
     private Integer id; 

     public void setAge(Integer age) 
     { 
      this.age = age; 
     } 

     public Integer getAge() 
     { 
      return age; 
     } 

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

     public String getName() 
     { 
      return name; 
     } 

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

     public Integer getId() 
     { 
      return id; 
     } 
    } 

接口,StudentDAO(爲DAO邏輯):

package com.tutorialspoint; 

import java.util.List; 
import javax.sql.DataSource; 

public interface StudentDAO 
{ 
    /** 
     * This is the method to be used to initialize 
     * database resources ie. connection. 
    */ 
    public void setDataSource(DataSource ds); 

    /** 
     * This is the method to be used to create 
     * a record in the Student table. 
    */ 
    public void create(String name, Integer age); 

    /** 
     * This is the method to be used to list down 
     * a record from the Student table corresponding 
     * to a passed student id. 
    */ 
    public Student getStudent(Integer id); 

    /** 
     * This is the method to be used to list down 
     * all the records from the Student table. 
    */ 
    public List<Student> listStudents(); 

    /** 
     * This is the method to be used to delete 
     * a record from the Student table corresponding 
     * to a passed student id. 
    */ 
    public void delete(Integer id); 

    /** 
     * This is the method to be used to update 
     * a record into the Student table. 
    */ 
    public void update(Integer id, Integer age); 
} 

然後,類StudentJDBCTemplate(到器具StudentDAO) :

package com.tutorialspoint; 

import java.util.List; 
import javax.sql.DataSource; 
import org.springframework.jdbc.core.JdbcTemplate; 

public class StudentJDBCTemplate implements StudentDAO 
{ 
    private DataSource dataSource; 
    private JdbcTemplate jdbcTemplateObject; 

    public void setDataSource(DataSource dataSource) 
    { 
     this.dataSource = dataSource; 
     this.jdbcTemplateObject = new JdbcTemplate(dataSource); 
    } 

    public void create(String name, Integer age) 
    { 
     String SQL = "insert into Student (name, age) values (?, ?)"; 
     jdbcTemplateObject.update(SQL, name, age); 
     System.out.println("Created Record Name = " + name + " Age = " + age); 
     return; 
    } 

    public Student getStudent(Integer id) 
    { 
     String SQL = "select * from Student where id = ?"; 
     Student student = jdbcTemplateObject.queryForObject(SQL, 
     new Object[]{id}, new StudentMapper()); 

     return student; 
    } 

    public List<Student> listStudents() 
    { 
     String SQL = "select * from Student"; 
     List <Student> students = jdbcTemplateObject.query(SQL, new StudentMapper()); 
     return students; 
    } 

    public void delete(Integer id) 
    { 
     String SQL = "delete from Student where id = ?"; 
     jdbcTemplateObject.update(SQL, id); 
     System.out.println("Deleted Record with ID = " + id); 
     return; 
    } 

    public void update(Integer id, Integer age) 
    { 
     String SQL = "update Student set age = ? where id = ?"; 
     jdbcTemplateObject.update(SQL, age, id); 
     System.out.println("Updated Record with ID = " + id); 
     return; 
    } 
} 

第三類:StudentMapper(以映射到MySQL分貝學生):

package com.tutorialspoint; 

import java.sql.ResultSet; 
import java.sql.SQLException; 
import org.springframework.jdbc.core.RowMapper; 

public class StudentMapper implements RowMapper<Student> 
{ 
    public Student mapRow(ResultSet rs, int rowNum) throws SQLException 
    { 
     Student student = new Student(); 
     student.setId(rs.getInt("id")); 
     student.setName(rs.getString("name")); 
     student.setAge(rs.getInt("age")); 

     return student; 
    } 
} 

末級,MainApp(運行程序):

package com.tutorialspoint; 

import java.util.List; 

import org.springframework.context.ApplicationContext; 
import org.springframework.context.support.ClassPathXmlApplicationContext; 
import com.tutorialspoint.StudentJDBCTemplate; 

public class MainApp { 
    public static void main(String[] args) { 
     ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml"); 

     StudentJDBCTemplate studentJDBCTemplate = 
     (StudentJDBCTemplate)context.getBean("studentJDBCTemplate"); 

     System.out.println("------Records Creation--------"); 
     studentJDBCTemplate.create("Zara", 11); 
     studentJDBCTemplate.create("Nuha", 2); 
     studentJDBCTemplate.create("Ayan", 15); 

     System.out.println("------Listing Multiple Records--------"); 
     List<Student> students = studentJDBCTemplate.listStudents(); 

     for (Student record : students) { 
     System.out.print("ID : " + record.getId()); 
     System.out.print(", Name : " + record.getName()); 
     System.out.println(", Age : " + record.getAge()); 
     } 

     System.out.println("----Updating Record with ID = 2 -----"); 
     studentJDBCTemplate.update(2, 20); 

     System.out.println("----Listing Record with ID = 2 -----"); 
     Student student = studentJDBCTemplate.getStudent(2); 
     System.out.print("ID : " + student.getId()); 
     System.out.print(", Name : " + student.getName()); 
     System.out.println(", Age : " + student.getAge()); 
    } 
} 

最後,豆類文件來配置數據庫連接:

<?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-3.0.xsd "> 

    <!-- Initialization for data source --> 
    <bean id="dataSource" 
     class = "org.springframework.jdbc.datasource.DriverManagerDataSource"> 
     <property name = "driverClassName" value = "com.mysql.jdbc.Driver"/> 
     <property name = "url" value = "jdbc:mysql://localhost:3306/springtraining"/> 
     <property name = "username" value = "***"/> 
     <property name = "password" value = "***"/> 
    </bean> 

    <!-- Definition for studentJDBCTemplate bean --> 
    <bean id = "studentJDBCTemplate" 
     class = "com.tutorialspoint.StudentJDBCTemplate"> 
     <property name = "dataSource" ref = "dataSource" />  
    </bean> 

</beans> 

的教程非常清楚,如果我嘗試它有一個完美的執行沒有錯誤,MySQL DB正確更新。

我的問題是關於這個項目的一個可能的變化。更具體地講:

  1. 如果我想使用application.properties文件(如通過春季啓動給出),是這個正確的sintax?

    spring.datasource.driver類名= com.mysql.jdbc.Driver spring.datasource.url = JDBC:MySQL的://本地主機:3306/springtraining spring.datasource.username = * 彈簧.datasource.password = *

  2. 如果我不想使用RowMapper類,是否正確使用Spring提供的BeanPropertyRowMapper?

  3. 沒有豆文件(如果我使用,在這個例子中,application.properties,我羽根沒有必要的話),我怎麼能替換MainApp此行:

    ApplicationContext的背景=新的ClassPathXmlApplicationContext ( 「beans.xml文件」);

    StudentJDBCTemplate studentJDBCTemplate = 
        (StudentJDBCTemplate)context.getBean("studentJDBCTemplate"); 
    

,使這樣的應用程序可執行文件?

回答

0

首先,我建議您不要使用application.properties文件來學習如何操作。我們生活在21世紀,其中Spring-boot允許我們在MySpringBootApplication類中聲明jdbc dataSource@Bean,並帶有數據庫憑證。看看怎麼做here

其次,我建議不要使用jdbcTemplate,除非你沒有時間。標記我的話,如果碰巧調試 - 這將是噩夢。因此,嘗試使用 純Jdbc並添加彈簧配置。

樣品例如如何做到這一點:

StudentDAO接口

public interface StundentDAO { 

    void addStudent(String name, String surname); 

    List<Student> findStudents(); 
} 

JdbcStudentDAO實施

@Repository 
    public class JdbcStudentDAO implements StudentDAO { 

    //[IMPORTANT] import javax.sql.datasource package (?) 
    private Datasource datasource; 

    @Autowire 
    public JdbcStudentDAO(Datasource datasource) { 
     this.datasource = datasource; 
    } 

    @Override 
    public void addStudent(String name, String surname) { 
     String query = "INSERT INTO Students VALUES (?,?)"; 
     try(Connection connection = datasource.getConnection()) { 
      try(PreparedStatement statement = connection.preparedStatement(query)) { 
       statement.setString(1, name); 
       statement.setString(2, surname); 
       statement.executeUpdate(); 
      } 
     } catch(SQLException e) { 
      e.printStacktrace(); 
     } 
    } 

    @Override 
    public List<Student> findStudents() { 
     String query = "SELECT * FROM Students"; 
     Student student = null; //will be used soon as DTO 
     List<Student> listOfStudents = null; 
     try(Connection connection = datasource.getConnection()) { 
      try(PreparedStatement statement = connection.preparedStatement(query)) { 
       try(ResultSet rs = statement.executeQuery()) { 
        listOfStudents = new ArrayList<>(); 
        while(rs.next()) { 
         student = new Student(
          rs.getString("name"); 
          rs.getString("surname"); 
         ); 
        } 
        listOfStudents.add(student); 
       } 
      } 
     } catch(SQLException e) { 
      e.printStacktrace(); 
     } 
     return listOfStudents; 
    } 
} 

請注意,dataSource只做數據庫連接(見的。鏈接)

祝你好運!

+0

首先,tnx爲響應。 然後,我知道我們有Spring Boot,但由於某種原因,我的老闆可能不想使用Boot,所以我已經搜索了一個方法輸入它。 無論如何,你的反應是清晰和完整的,我很欣賞非常muach。 –

相關問題