Spring JDBC使用application.properties文件 [英] Spring JDBC using application.properties file
问题描述
我正在训练自己有关Spring JDBC的知识,并且正在遵循此教程: Spring JDBC示例.
i'm training myself on Spring JDBC and i'm following this tutorials: Spring JDBC Example.
这些教程非常好,可以执行代码,我没问题.
The tutorials is very good and executing the code, i have no problem.
简单和方便,我在这里引用代码.
Fof simplicity and convenience, I quote here the code.
第一堂课,学生(要存储在db中的实体):
First class, Student (the entity to store in 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逻辑):
Interface, StudentDAO (for DAO logic):
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):
Then, the class StudentJDBCTemplate (to implements 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 db Student):
Third class: StudentMapper (to mapping to MySQL db Student):
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类(运行应用程序):
Last class, MainApp (run the application):
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());
}
}
最后,使用Beans文件配置数据库连接:
Finally, the Beans file to configure database connection:
<?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已正确更新.
The tutorial is very clear and if i try it, there is a perfect execution without error and the MySQL Db is correctly updated.
我的问题是关于这个项目的可能变化.更具体地说:
My questions are about a possible variation of this project. More specifically:
-
如果我要使用application.properties文件(如Spring boot给出的文件),这是否是正确的sintax?
If i want use the application.properties file (as that given by Spring boot), is it this the correct sintax?
spring.datasource.driver-class-name = com.mysql.jdbc.Driver spring.datasource.url = jdbc:mysql://localhost:3306/springtraining spring.datasource.username = * spring.datasource.password = *
spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/springtraining spring.datasource.username=* spring.datasource.password=*
如果我不想使用RowMapper类,是否正确使用Spring给出的BeanPropertyRowMapper类?
If i don't want use the RowMapper class, is it correct use that one given by spring, the BeanPropertyRowMapper?
没有Beans文件(如果我在此示例中使用application.properties,则无需此文件),如何在MainApp中替换以下行:
Without the Beans file (if i use, for this example, the application.properties, i hane no need of it), how can i replace in the MainApp this rows:
ApplicationContext context =新的ClassPathXmlApplicationContext("Beans.xml");
ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
StudentJDBCTemplate studentJDBCTemplate =
(StudentJDBCTemplate)context.getBean("studentJDBCTemplate");
并使应用程序可执行吗?
and making so the applications executable?
推荐答案
首先,我建议您学习如何在没有application.properties
文件的情况下进行操作.我们生活在21世纪,其中Spring-boot
允许我们使用MySpringBootApplication
类中的数据库凭据将jdbc dataSource
声明为@Bean
.请参见此处
Firstly, I'd advise you to learn how to do it without application.properties
file. We live in 21rst century, where Spring-boot
allows us to declare jdbc dataSource
as @Bean
with database credentials in MySpringBootApplication
class. See how to do it here
其次,除非您没有时间,否则我建议不要使用jdbcTemplate
.写下我的话,如果碰巧要调试-那将是一场噩梦.所以尝试使用
纯Jdbc,并增加了spring配置.
Secondly, i'd advise not to use jdbcTemplate
unless you don't have time. Mark my words, if happens to debug - it would be nightmare. So try to use
pure Jdbc with addition of spring configuration.
示例示例如何实现:
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
仅执行数据库连接.(请参见链接)
Please note, that dataSource
does only Database connectivity.(see the link)
祝你好运!
这篇关于Spring JDBC使用application.properties文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!