|
| 1 | +package com.study.templatetest; |
| 2 | + |
| 3 | +import com.study.entity.Student; |
| 4 | +import com.study.until.JDBCUntil; |
| 5 | +import com.study.until.JDBCUntilsForJDBCTempLate; |
| 6 | +import org.junit.Test; |
| 7 | +import org.springframework.jdbc.core.BeanPropertyRowMapper; |
| 8 | +import org.springframework.jdbc.core.JdbcTemplate; |
| 9 | +import org.springframework.jdbc.core.RowMapper; |
| 10 | +import org.springframework.transaction.annotation.Transactional; |
| 11 | + |
| 12 | +import java.sql.Connection; |
| 13 | +import java.sql.PreparedStatement; |
| 14 | +import java.sql.ResultSet; |
| 15 | +import java.sql.SQLException; |
| 16 | +import java.util.List; |
| 17 | +import java.util.Map; |
| 18 | + |
| 19 | +public class TemplateDemo { |
| 20 | + |
| 21 | + private JdbcTemplate jdbcTemplate = new JdbcTemplate(JDBCUntilsForJDBCTempLate.dataSource); |
| 22 | + |
| 23 | + |
| 24 | + @Test |
| 25 | + public void TestQuery() { |
| 26 | + |
| 27 | + RowMapper<Student> rowMapper = new RowMapper<Student>() { |
| 28 | + @Override |
| 29 | + public Student mapRow(ResultSet resultSet, int i) throws SQLException { |
| 30 | + Student student = new Student(); |
| 31 | + student.setName(resultSet.getString("name")); |
| 32 | + student.setId(resultSet.getInt("id")); |
| 33 | + return student; |
| 34 | + } |
| 35 | + }; |
| 36 | + List<Student> query = jdbcTemplate.query("select * from student", rowMapper); |
| 37 | + System.out.println(query); |
| 38 | + } |
| 39 | + |
| 40 | + @Test |
| 41 | + public void TestTran() { |
| 42 | + Connection connection = null; |
| 43 | + try { |
| 44 | + //jdbctemplate 想要事务的还是要获取原来的connection不知道是否有其他的办法 |
| 45 | + connection = jdbcTemplate.getDataSource().getConnection(); |
| 46 | + connection.setAutoCommit(false); |
| 47 | + PreparedStatement preparedStatement = connection.prepareStatement("update student set name='tranException' where id=?"); |
| 48 | + preparedStatement.setInt(1, 1); |
| 49 | + PreparedStatement preparedStatement1 = connection.prepareStatement("update student set name ='tranException1' where id=?"); |
| 50 | + preparedStatement1.setInt(1, 2); |
| 51 | + preparedStatement.executeUpdate(); |
| 52 | + int i = 1 / 0; |
| 53 | + preparedStatement1.executeUpdate(); |
| 54 | + connection.commit(); |
| 55 | + } catch (SQLException e) { |
| 56 | + e.printStackTrace(); |
| 57 | + } |
| 58 | + |
| 59 | + |
| 60 | + } |
| 61 | + |
| 62 | + @Test |
| 63 | + public void queryss() { |
| 64 | + |
| 65 | + //getName 写错了 其实就相当于C#中的属性错了 反射 找到当前字段的 getset方法 然后执行这个方法 因为写错了 找不到 |
| 66 | + // 所以.......就有问题了 |
| 67 | + List<Student> query = jdbcTemplate.query("select * from student where id=1", new BeanPropertyRowMapper<Student>(Student.class)); |
| 68 | + System.out.println(query); |
| 69 | + } |
| 70 | +} |
0 commit comments