导包
- aopalliance-1.0.jar
- aspectjrt-1.8.10.jar
- aspectjweaver-1.8.10.jar
- c3p0-0.9.5.2.jar
- commons-logging-1.1.1.jar
- mchange-commons-java-0.2.11.jar
- mysql-connector-java-5.1.30.jar
- spring-aop-4.3.10.RELEASE.jar
- spring-beans-4.3.10.RELEASE.jar
- spring-context-4.3.10.RELEASE.jar
- spring-core-4.3.10.RELEASE.jar
- spring-expression-4.3.10.RELEASE.jar
- spring-jdbc-4.3.10.RELEASE.jar
- spring-tx-4.3.10.RELEASE.jar
操作数据库的步骤
- 创建一个pojo类,与数据库对应
- 创建一个接口
- 编写dao类,添加一个JdbcTemplate属性,操作数据库,还需要自定义映射类,实现接口
public class StudentImpl implements StudentMapper{
//利用spring提供的工具类实现对数据的操作
private JdbcTemplate jdbcTemplate;
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Override
public List<Student> all() {
String sql = "select * from student";
//jdbcTemplate.query(sql, 需要自定义映射规则)
List<Student> students = jdbcTemplate.query(sql,new MyResult());
return students;
}
//自定义映射
class MyResult implements RowMapper<Student>{
@Override
public Student mapRow(ResultSet rs, int index) throws SQLException {
Student student = new Student();
student.setSid(rs.getInt("sid"));
student.setName(rs.getString("sname"));
student.setCid(rs.getInt("cid"));
return student;
}
}
@Override
public void insert(Student student) {
String sql = "insert into student values(?,?,?)";
jdbcTemplate.update(sql, new Object[] {student.getSid(),student.getName(),student.getCid()});
}
}
复制代码
- 引入配置文件
<!-- 1.先配置连接池:spring-jdbc基于连接池技术实现连接数据库 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3308/mybatis?useUnicode=true&characterEncoding=UTF-8"></property>
<property name="user" value="root"></property>
<property name="password" value="123456"></property>
<property name="initialPoolSize" value="5"></property>
<property name="maxPoolSize" value="10"></property>
<property name="maxStatements" value="20"></property>
</bean>
<!-- 2.创建JdbcTemplate -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 3.dao -->
<bean id="dao" class="com.dyr.dao.StudentImpl">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
<!-- 4.service -->
<bean id="service" class="com.dyr.service.StudentService">
<property name="dao" ref="dao"></property>
</bean>
复制代码
转载于:https://juejin.im/post/5c7f6ea66fb9a049f746f530