我正在对 Spring JDBC 进行 self 培训,并且正在遵循本教程:Spring JDBC Example .
教程非常好,执行代码没有问题。
为了简单和方便,我在这里引用代码。
第一类,学生(存储在数据库中的实体):
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 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
(运行应用程序):
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文件:
<?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 数据库已正确更新。
我的问题是关于该项目的可能变化。更具体地说:
如果我想使用
application.properties
文件(如 SpringBoot 给出的那样),这是正确的语法吗?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
是否正确? ?如果没有 Beans 文件(如果我在本例中使用
application.properties
,我就不需要它),我如何在MainApp
中替换这行:ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
StudentJDBCTemplate studentJDBCTemplate = (StudentJDBCTemplate)context.getBean("studentJDBCTemplate");
并使应用程序可执行?
最佳答案
首先,我建议您学习如何在没有 application.properties
的情况下做到这一点文件。我们生活在 21 世纪,Spring-boot
允许我们声明 jdbc dataSource
如@Bean
数据库凭据位于 MySpringBootApplication
类(class)。看看怎么做 here
其次,我建议不要使用jdbcTemplate
除非你没有时间。记住我的话,如果碰巧进行调试——那将是一场噩梦。所以尝试使用
纯Jdbc加上spring配置。
如何做到这一点的示例:
StudentDAO 接口(interface)
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
仅进行数据库连接。(请参阅链接)
祝你好运!
关于mysql - Spring JDBC 使用 application.properties 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43181853/