Spring JDBC
Spring's JDBC database module is responsible for resource management and error handling, greatly simplifies the operation of the database developers, allowing developers freed from tedious database operations, thus more energy into the business processes.
Spring JdbcTemplate Analysis:
For the operation of the database, the Spring Framework provides JdbcTemplate class, which is the basis for the Spring Framework data abstraction layer, other higher level abstract class is built on top of JdbcTemplate.
Spring JDBC configuration
SpringJDBC module consists of four packets, namely the Core (core), the dataSource (packet data source), Object (object packages) and suppor (Support Package)
Core: contains the JDBC core functionality, including JdbcTemplate etc.
DataSource: utility class access to data sources, it has to achieve a variety of data sources
Object: an object-oriented access to databases, which allows to execute the query and returns a result of business objects, attributes may be between the columns and the business object in the data table mapping query results.
Support: comprising the core and object, for example, an exception conversion SQLException
Examples of code demonstrates:
Have a database and data tables
Write interface methods:
public interface PersonDao {
// Add to
public int addPerson(Person p);
// Update
public int updatePerson(Person p);
// delete
public int deletePerson(int id);
// According to id
public Person findPersonById(int id);
// query all
public List<Person> findAllPerson();
}
Write interface classes:
public class PersonDaoImpl implements PersonDao {
// declare JdbcTemplate properties and their setter methods
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
// Add to
@Override
public int addPerson(Person p) {
// TODO Auto-generated method stub
// define sql
String sql = "insert into Person(name,pwd) value(?,?)";
// define array to store parameters sql statement
Object[] obj = new Object[] { p.getName(), p.getPwd() };
int num = this.jdbcTemplate.update(sql, obj);
return num;
}
@Override
public int updatePerson(Person p) {
// TODO Auto-generated method stub
// define sql
String sql = "update Person set name=?,pwd=? where id=?";
// define array to store parameters sql statement
Object[] obj = new Object[] { p.getName(), p.getPwd(), p.getId() };
int num = this.jdbcTemplate.update(sql, obj);
return num;
}
@Override
public int deletePerson(int id) {
// TODO Auto-generated method stub
// define sql
String sql = "delete from Person where id=?";
int num = this.jdbcTemplate.update(sql, id);
return num;
}
@Override
public Person findPersonById(int id) {
// TODO Auto-generated method stub
// define a sql statement
String sql = "select * from Person where id=?";
// Create a new object is BeanPropertyRowMapper
RowMapper<Person> rowMapper = new BeanPropertyRowMapper<Person>(
Person.class);
// The id is bound to sql statement you can query the database and mapping
return this.jdbcTemplate.queryForObject(sql, rowMapper, id);
}
@Override
public List<Person> findAllPerson() {
// TODO Auto-generated method stub
String sql = "select * from Person";
// Create a new object is BeanPropertyRowMapper
RowMapper<Person> rowMapper = new BeanPropertyRowMapper<Person>(
Person.class);
// The id is bound to sql statement you can query the database and mapping
return this.jdbcTemplate.query(sql, rowMapper);
}
}
Write entity classes:
public class Person {
private int id;
private String name;
private String pwd;
public Person() {
super();
// TODO Auto-generated constructor stub
}
public Person(int id, String name, String pwd) {
super();
this.id = id;
this.name = name;
this.pwd = pwd;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", pwd=" + pwd + "]";
}
}
Write test classes:
public class testDemo {
@Test
public void method(){
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
JdbcTemplate jdbcTemplate = (JdbcTemplate) app.getBean("jdbcTemplate");
// use the execute () method executes sql statements to create table Student
jdbcTemplate.execute("create table student("+
"id int primary key,"+
"username varchar(50),"+
"balance double)");
System.out.println ( "Creating sudent table finish ...");
}
@Test
public void addMethod2(){
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
PersonDao pd = (PersonDao) app.getBean("personDao");
Person p = new Person();
p.setName ( "Wei Yan");
p.setPwd("123");
int num = pd.addPerson(p);
System.out.println(num);
}
@Test
public void updateMethod3(){
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
PersonDao pd = (PersonDao) app.getBean("personDao");
Person p = new Person();
p.setId(1);
p.setName ( "Zhao");
p.setPwd("123");
int num = pd.updatePerson(p);
System.out.println(num);
}
@Test
public void deleteMethod4(){
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
PersonDao pd = (PersonDao) app.getBean("personDao");
Person p = new Person();
p.setId(1);
int num = pd.deletePerson(2);
System.out.println(num);
}
@Test
public void findPersonByIdMethod5(){
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
PersonDao pd = (PersonDao) app.getBean("personDao");
Person findPersonById = pd.findPersonById(1);
System.out.println(findPersonById);
}
@Test
public void findAllPersonMethod6(){
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
PersonDao pd = (PersonDao) app.getBean("personDao");
List<Person> findAllPerson = pd.findAllPerson();
for(Person p : findAllPerson){
System.out.println(p);
}
}
}
Write configuration file:
<! - 1, configuration data source ->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<-! Database-driven ->
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<! - link to the database url ->
<property name="url" value="jdbc:mysql://localhost:3306/demo" />
<! - username link to the database ->
<property name="username" value="root" />
<-! Password link the database ->
<property name="password" value="123456" />
</bean>
<-! 2, configure JDBC Templates ->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<! - default must use a data source ->
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="personDao" class="com.bdqn.cn.dao.PersonDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplate" />
</bean>
Spring 's transaction management
Transaction Management way:
- Programmatic transaction management
Transaction management is achieved by writing code, including the definition of the beginning of the transaction, the transaction after the normal and abnormal commit transaction rollback
- Declarative transaction management
Transaction management is achieved through AOP technology, the main idea is to manage affairs as an "aspect" code written separately and then by AOP transaction management technology will "cut" the code woven into the business target class
Declarative transaction management in two ways:
1, based on xml declarative transaction management approach is relevant statement by the configuration of business rules in the configuration file to achieve. Spring2.0 later, a configuration transaction x namespace for the next tx namespace <tx: advice> element to configure the notification transaction (enhancement processing). When: After <tx advice> element configures the enhanced processing services, you can write by AOP configuration, make Spring automatically generate the proxy target.