Spring and jdbc annotation form

Spring and JDBC 

2011-05-16 21:54:18| Category: spring | Label: spring jdbc Summary Daquan | Font size subscription
JDBC is the basis for the connection of the java part of the database, come to my blog to review him, the following is the jdbc Summary of some knowledge points.
1. Configuration file
We need to configure the data source in the configuration file. The configuration format of the data source is roughly as follows:
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost:3306/student"/>
    <property name="username " value="root"/>
    <property name="password" value="root"/>
  </bean>
Of course, we can also configure other connection pool information, such as:
<!-- The initial value when the connection pool starts -->


<property name="maxActive" value="100"/>
<!-- The maximum idle value. After a peak time, the connection pool can slowly release some of the unused connections until it is reduced to maxIdle So far -->
<property name="maxIdle" value="100"/>
<!-- Minimum idle value. When the number of idle connections is less than the threshold, the connection pool will pre-apply for some connections to avoid flooding It's too late to apply -->
<property name="minIdle" value="100"/>
We often need to write the corresponding information into a file in practical applications. If you need to modify it, you can directly modify this file, and I will list it below. Out method
1) Create jdbc.properties file
driverClassName=com.mysql.jdbc.Driver
url=jdbc\:mysql\://localhost\:3306/test
username=root
password=root 2) Reference <context
in configuration file :
property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource" class="org.apache.commons.dbcp. BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="${driverClassName}"/>
    <property name="url" value="${url}"/>
    <property name="username" value="${username}"/ >
    <property name="password" value="${password}"/>
  </bean>
Note that adding the classpath to the location means that the false path of the web application is used. In value, we can get it like an EL
expression.
2. JDBC usage
public class PersonServiceBean implements PersonService {
private JdbcTemplate jdbcTemplate;
@Resource
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
}
Explain the above code,

public List<Person> getAllPerson() {//查询list
List list=jdbcTemplate.queryForList("select * from employee");//如果要有条件查询,可以用jdbcTemplate.queryForList(sql, args, argTypes)
return list;
}
public Person getPerson(Integer empid) {//查询object
Person person=(Person)jdbcTemplate.queryForObject("select * from employee where empid=?",new Object[]{empid},
new RowMapper(){
public Object mapRow(ResultSet rs, int index) throws SQLException {
Person person=new Person();
person.setEmpid(rs.getInt("empid"));
person.setEmpname(rs.getString("empname"));
person.setDepartid(rs.getInt("departid"));
return person;
}
}
);
return person;
}
public void save(Person person) {//Insert
jdbcTemplate.update("insert into employee(empname,departid) values(?,?)",new Object[]{person.getEmpname(),person.getDepartid()}
,new int[]{Types.VARCHAR,Types.INTEGER}
);
}
public void update(Person person) {//Update
jdbcTemplate.update("update employee set empname=? where empid=?",new Object[]{ person.getEmpname(),person.getEmpid()},
new int[]{Types.VARCHAR,Types.INTEGER});
}
4. Transaction management
In our above program, we found that we did not manage transactions, In fact, we use the transaction management of JdbcTemplate. In actual development, we need to hand over the transaction to spring for management. Here are some summaries:
1) Configuration file
<beans xmlns="http://www.springframework.org/ schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
</beans>
First introduce the tx namespace, the red part of the text above. Also add the following statement:
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
   <property name="dataSource" ref="dataSource"/> <!--dataSource is data id of the source configuration-->
  </bean>
  <tx:annotation-driven transaction-manager="txManager"/>
2) jdbc class
@Transactional //The transaction is handed over to the spring container for management, and spring opens the transaction before the method ends. Close the transaction after the method ends
public class PersonServiceBean implements PersonService {
private JdbcTemplate jdbcTemplate;
@Resource
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public void deletePerson(Integer empid) {
jdbcTemplate.update("delete from employee where empid=?",new Object[]{empid}
,new int[]{Types.INTEGER}
);
}
}
Add @Transactional to the class to define the transaction of this class It is managed by spring. After adding this annotation, spring's transaction management is added to each method by default. The transaction is opened when the method starts, and the transaction is closed when the method ends.
Many query methods do not have transaction management. If transaction management is added, the efficiency will be reduced. At this time, we need to configure annotations on the methods:
@Transactional(propagation=Propagation.NOT_SUPPORTED)
public List<Person> getAllPerson() {
List list=jdbcTemplate.queryForList("select * from employee");
return list;
}
When it comes to propagation, I will talk about several properties of propagation:
A.REQUIRED
is our most commonly used propagation property and is also the default value (method It defaults to him without modification), and the business method needs to run in a transaction. If the method is running, it is already in a transaction, then join the transaction, otherwise create a new transaction for itself.
B.NOT_SUPPORTED
Declare methods do not require transactions. If the method is not associated with a transaction, the container will not open a transaction for it. If the method is called within a transaction, the transaction is suspended, and the original transaction resumes execution after the method call ends.
The C.REQUIRESNEW
attribute indicates that the business method will always initiate a new transaction for itself regardless of whether there is a transaction. If the method is already running in a transaction, the original transaction will be suspended, a new transaction will be created, and the new transaction will not end until the method execution ends, and the original transaction will resume execution.
D.MANDATORY
This attribute specifies that business methods can only be executed in an existing transaction, and business methods cannot initiate their own transactions. If the business method is called without a transaction, the container will throw an exception.
The E.SUPPORTS
transaction attribute indicates that if a business method is called within the scope of a transaction, the method becomes part of the transaction. If a business method is called outside the scope of a transaction, the method executes without a transaction.
F.Never
specifies that business methods must never be executed within the scope of a transaction. If the business method is executed in a transaction, the container will throw an exception. Only the business method is not associated with any transaction, it can be executed normally.
G.NESTED
If an active transaction exists, it runs in a nested transaction. If there is no active transaction, it is executed according to the REQUIRED attribute. It uses a single transaction, which has multiple savepoints that can be rolled back . The rollback of the inner transaction does not affect the outer transaction. It only works on the DataSourceTransactionManager transaction manager. The following is his implementation mechanism:
Connection conn = null;
try {
    conn.setAutoCommit(false);
    Statement stmt = conn.createStatement();
    stmt.executeUpdate("update person set name='888' where id=1");//语句一
    Savepoint savepoint = conn.setSavepoint();
    try{  
            conn.createStatement().executeUpdate("update person set name='222' where sid=2");//语句二
    }catch(Exception ex){
            conn.rollback(savepoint);   
     }
      stmt.executeUpdate("delete from person where id=9");//语句三
      conn.commit();
       stmt.close();
    } catch (Exception e) {
         conn.rollback();
     }finally{
               try {
    if(null!=conn && !conn.isClosed()) conn.close();
                } catch (SQLException e) { e.printStackTrace(); }
     }
}
From the above mechanism, we can see that if statement 2 fails to execute, it will not be saved to the database, but statements 1 and 3 will be saved to the data , but if either statement one or three fails, it will not be saved in the database. What do you mean? That is to say, this applies to one of our requests. The successful execution of a certain business logic cannot affect our business logic (the successful execution of statement 2 will not affect statements 1 and 3).
3) If the execution fails? Will there be a rollback?
After doing this, we can't help but think of a question, if one of the above methods is abnormal during execution? Will there be a rollback? The answer is that if our exception is an unchecked exception, he will rollback, and if it is a checked exception, he will not rollback.
So how to modify the default return conditions?
Modify the rollback in normal exceptions
@Transactional(rollbackFor=Exception.class)
Modify do not rollback in runtime exceptions
@Transactional(noRollbackFor=RuntimeException.class)
5. Finally, briefly introduce the transaction management based on configuration files:
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
















When I query the object above, I use the queryForObject method. The third parameter of this method is an anonymous function, and the function puts the query results into our bean one by one. In fact, there are simpler encapsulation classes in spring to complete this function for us. As follows:
Person person=(Person)jdbcTemplate.queryForObject("select * from employee where empid=?", new Object[]{empid}, new BeanPropertyRowMapper(Person.class));
return person;
use new BeanPropertyRowMapper(Person.class ) method, he completed the filling function for us.
At this time, we need to think about how he recognized it? I haven't done the experiment, and I don't think it's necessary, because according to the specification, the property name in the bean is the same as the field name in the database. If you want nothing to do, don't treat them the same.
Of course, we often like such fields in the database: t_name, t_age, if it is such a field, we will not have to underline it in the bean, right? Of course not, it is very likely that our field names in the database are called tname, tag.
At this time, in order to be foolproof, what should we do? At this time, you can use an alias:
Select t_name as tname, t_age as age from user
2) Querying multiple objects When the query
condition to be queried contains multiple results, you need to use the query, of course, the same as above.
person=(Person)jdbcTemplate.query("select * from employee",new BeanPropertyRowMapper(Person.class));
Since there are no parameters, the method without the array is used.
3) Querying queryForInt of a single attribute int
If the attribute to be queried is int, you can use the queryForInt method.
String sql="select count(*) from employee";
int count=jdbcTemplate.queryForInt(sql);
4) queryForObject
for querying a single attribute If you want to query a single attribute and it is not an int, you can use queryForObject to transform it.
public String getName(int empid) {
String sql="select empname from employee where empid=?";
Object obj=jdbcTemplate.queryForObject(sql, new Object[]{empid}, new int[]{Types.INTEGER},String .class);
return (String)obj;
}
5) When there is no bean, you can use queryForMap to query a single set of data. The
return is a map, and the map corresponds to the corresponding field name and value. When we do not have a bean, we can use this method
6) When there is no bean, you can use queryForList to query multiple sets of data. The
return is a List, and the map is placed in the list.
7) The update method of addition, deletion and modification
public void save(Person person) {
jdbcTemplate.update("insert into employee(empname, departid) values(?,?)",new Object[]{person.getEmpname(),person.getDepartid()}
,new int[]{Types.VARCHAR,Types.INTEGER}
);
}
8) Use of namespace
public User findUser(User user) {
String sql = "select id, name, money, birthday from user "
+ "where money > :m and id < :id";
Map params = new HashMap();
params.put(" m", user.getMoney());
params.put("id", user.getId());
Object u = named.queryForObject(sql, params, new BeanPropertyRowMapper(
User.class));
return (User) u;
}
在map中填值,进行转换
public User findUser1(User user) {
String sql = "select id, name, money, birthday  from user "
+ "where money > :money and id < :id";
SqlParameterSource ps = new BeanPropertySqlParameterSource(user);
Object u = named.queryForObject(sql, ps, new BeanPropertyRowMapper(
User.class));
return (User) u;
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327084384&siteId=291194637