SSM framework curriculum (four) - SpringJDBC


A .Spring treatment of abnormal jdbc

Spring to adopt certain exceptions, such as: SQLException, unified converted into its own exception type, these exceptions to DataAccessException as a parent class, they wrap the original exception object, situation losing the original error message does not appear. And inherited from RuntimeException DataAccessException of non abnormalities, it does not use the code in the process, we can use the interceptor unified control process in the outermost layer.


II. Acquire a data source DataSource

There are three ways to get data source:

  1. The DataSource from JNDI (need to configure the server is not commonly used in the configuration file)
  2. Obtaining a third-party connection pool DataSource, Spring achieved in the third class dependent package comprising two packet data source implementation classes, the first is the DBCP, C3P0 second is, can the two kinds thereof in the xml configuration file the DataSource
  3. Connecting the DataSource DriverManagerDataSource obtained (generally not applicable)

III. DataSource configured in two ways

3.1 DBCP for configuration datasource

  1. Required jar package
  • commons-dbcp-1.4.jar
  • commons-pool-1.6.jar
  • spring-jdbc-5.1.3.RELEASE.jar
  • spring-tx-5.1.3.RELEASE.jar
    Baidu network disk Download: Download
    git Download: Download

2. Configure jdbc.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/javaweb
username=root
password=123456
maxActive=10
  1. Quoted local configuration files, and configuration data source
<!-- 引入本地配置文件 -->
<util:properties id="jdbc" location="classpath:config/jdbc.properties"></util:properties>
	
<!-- 配置dbpc数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
	<property name="driverClassName" value="#{jdbc.driver}"></property>
	<property name="url" value="#{jdbc.url}"></property>
	<property name="username" value="#{jdbc.username}"></property>
	<property name="password" value="#{jdbc.password}"></property>
	<property name="maxActive" value="#{jdbc.maxActive}"></property>
</bean>

4.DBCP common configuration

  1. BasicDataSource provided close () method to close the data source bold style , so that when the container is closed Spring, the data source can be properly closed simply configure destroy-method = "close" attribute bold style . In addition to the above properties the necessary data source, there are some common properties:
  2. defaultAutoCommit bold style : set returned from the data source connection whether the automatic submission mechanism , the default is true
  3. defaultReadOnly : set the data source is only read-only operations, the default is false;
  4. for maxActive : maximum number of database connections is connected, is set to 0, no limit;
  5. maxIdle : maximum number of connections waiting time, is set to 0, no limit;
  6. maxWait : The maximum number of seconds to wait , in milliseconds, over time they report an error message;
  7. validationQuery : connection is used to verify the success of the SQL query, to return at least one row of data;

3.2 C3P0 achieve DataSource Configuration

  1. Required jar package
  • c3p0-0.9.5.2.jar
  • mchange-commons-java-0.2.11.jar
    Baidu network disk Download: Download
    git Download: Download
  1. C3P0 and DBCP configuration substantially the same, then the knowledge of different attributes
  2. Common Attributes Configuration:
  1. driverClass
  2. jdbcrl
  3. user
  4. password
  5. initialPoolSize: Create a connection pool is initialized when the number of connections, default: 3
  6. minPoolSize: minimum number of connections in the connection pool maintained, default: 3
  7. maxPoolSize: maximum number of connections in the connection pool have, this value will exceed the total number of connections will not get a new connection if access to new connections, but other connections to wait for the release, so this value is likely to be a great design, default : 15
  8. acquireIncrement: the number of new database connection pool idle in the absence of one-off connection is created when available, default: 3
  9. maxIdleTime: maximum idle time for connections, if more than this time, a database connection has not been used, it will fall off the connection. If 0 is never disconnected, the default is 0;
  10. maxConnectionAge: Configuring the connection of survival time, over this time the connection will automatically disconnect the connection pool discarded.

Four .Spring and written in a way to support the preparation of DAO

  1. JdbcTemplate abstract class encapsulates common JDBC methods, where connections to obtain release of the package, etc., greatly simplifies the use of JDBC can effectively avoid errors such as forgetting to close the connection resource.
  2. Jdbc JdbcDaoSupport abstract class is a base class of data access object using programming techniques jdbc DAO parent class, and the Class Connection JdbcTemplate acquired object information, used when the object to be injected datasource.

Written by:

  1. Mode 1: DAO inherit JdbcDaoSupport, then get JdbcTemplate its target by getIdbcTemplate () method (this method has some invasive code, not recommended)
  2. Mode two :( recommended) not inherit the JdbcDaoSupport, configuration bean instantiating objects in a spring JdbcTemplate vessel, injecting a DAO implementation.

V. CURD operations using the database to achieve JdbcTemplate

  1. JdbcTemplate spring.xml disposed in the bean instance, it requires the use of spring-jdbc jar package
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" >
	<property name="dataSource" ref="dataSource"></property>
</bean>
  1. Creating the Entity Classes
public class User {
	private int userId;
	private String userName;
	private String password;
	private String phoneNumber;
//省略get和set方法
}
  1. Create a mapping class entity class, is used to specify the database entity class field mapping relationship , by RowMapper interfaces implemented, each row of data mapped to an instance of an object
public class UserMapper implements RowMapper<User>{

	@Override
	public User mapRow(ResultSet rs, int i) throws SQLException {
		User user = new User();
		user.setUserId(rs.getInt("userId"));
		user.setUserName(rs.getString("userName"));
		user.setPassword(rs.getString("password"));
		user.setPhoneNumber(rs.getString("phoneNumber"));
		System.out.println(i);
		return user;
	}
}
  1. Use @Repository DAO classes of notes
@Repository  //DAO注解类
public class UserDAO {
	
	@Autowired
	private JdbcTemplate jt;
	UserMapper userMapper = new UserMapper();
	
	public List<User> getAll(){
		String sql = "select * from user";
		Object[] obj = {};
		// 参数(sql语句,?参数,映射类)
		List<User> uList = jt.query(sql, obj, userMapper);
		return uList;
	}
	
	public User getOne() {
		String sql = "select * from user where userId = ?";
		Object[] obj = {1001};
		User user = jt.queryForObject(sql, obj,userMapper);
		return user;
	}
	
	public int delete(int userId) {
		String sql = "delete from user where userId=?";
		Object[] obj = {1003};
		int count = jt.update(sql,obj);
		return count;
	}
}
  1. Common methods:
Method name effect
queryForObject() Query a single data
query() Multiple data query returns a list
update() For performing add, modify and delete statements
batchUpdate() Execute batch related statements;
execute() It can be used to execute any SQL statement, typically used to execute DDL statements
Published 26 original articles · won praise 27 · views 6869

Guess you like

Origin blog.csdn.net/qq_40705355/article/details/98638521