spring - jdbc persistence layer, database operations

Two methods of operation of the database spring configuration database connection pool.

 

Generally do not use the spring to operate the database.

After using the mybatis spring and integration, mybatis responsible for operating the database

 

Database operations, the need to import spring-tx, mysql-connector jar package

 

  1, the traditional class integrated development

    Create package directly in connection pool class.

// (1) database connection pool configuration 
the DriverManagerDataSource dd = new new the DriverManagerDataSource ();
        
  dd.setDriverClassName("com.mysql.jdbc.Driver");
  dd.setUrl("jdbc:mysql:///book_db");
  dd.setUsername("root");
    dd.setPassword("6112783king");
        
@ (2) arranged to operate a database JdbcTemplate 
JdbcTemplate JT = new new JdbcTemplate ();
   jt.setDataSource(dd);
        
// (3) operation of the database 
   jt.execute ( " the SELECT * from ADMIN " )

  

   2, using the built-in database connection pool spring

    Configured in the spring configuration file inside

// Note imported class package. Here c3p0 use connection pooling. There are many connection pool 
<! - ( 1 ) using a database connection pool c3p0 -> <bean id="datasoure" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"></property> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/book_db"></property> <property name="user" value="root"></property> <property name="password" value="61112783king"></property> </bean> <-! ( 2 ) Configuration of JDBC spring template -> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="datasoure"></property> </bean>

   When Junit test, automatic assembly requires a jdbcTemplate

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(locations = "classpath:spring/application.xml")
public class text {
    
    // need to automatically assemble a the JdbcTemplate 
    @Autowired
    JdbcTemplate jd;
    
    @Test
    public void texts() {
        
        jd.execute("select * from admin");
    }
}

    

    Here the same can be imported properties file

   In the above need package path connection pools to: ComboPooledDataSource

      

  

  spring operation of the database

Guess you like

Origin www.cnblogs.com/huangcan1688/p/11871051.html