spring JdbcTemplate使用(データベースの恒久化一)

2750 ワード

目次
  • プロファイル
  • demo
  • JdbcTemplateはspringの中のjdbc操作です.必ず使用しないでください.
    設定ファイル
    
    
    
    
    	
    		
    		
    		
    		
    	
    	
    		
    	
    
    
    デモ
    public class DemoJdbcTemplate {
    	private static final Logger logger = LoggerFactory.getLogger(RunMainDbcp.class);
    
    	public static void main(String[] args) {
    		ApplicationContext context = new ClassPathXmlApplicationContext("day5/spring-config.xml");
    		JdbcTemplate jdbcTemplate = (JdbcTemplate) context.getBean("jdbcTemplate");
    		logger.debug(jdbcTemplate.toString());
    		logger.debug(" ");
    		// insertRole(jdbcTemplate);
    		logger.debug(" ");
    		// deleteRole(jdbcTemplate);
    		logger.debug(" ");
    		// updateRole(jdbcTemplate);
    		logger.debug(" ");
    		List role = getRole(jdbcTemplate);
    		logger.debug("{}", role);
    	}
    
    	private static List getRole(JdbcTemplate jdbcTemplate) {
    		String sql = "sELECT * from role where name like concat('%', ?, '%')";
    		Object[] args = {"wawa"};
    		List resultList = jdbcTemplate.query(sql, args, (rs, rownum) -> {
    			Role role = new Role();
    			role.setId(rs.getInt("id"));
    			role.setName(rs.getString("name"));
    			role.setDesc(rs.getString("desc"));
    			return role;
    		});
    		return resultList;
    	}
    
    	private static void updateRole(JdbcTemplate jdbcTemplate) {
    		String sql = "update role set name = ?, `desc` = ? where id = ?";
    		Object[] args = {"wawa", "   ", -1};
    		jdbcTemplate.update(sql, args);
    	}
    
    	private static void deleteRole(JdbcTemplate jdbcTemplate) {
    		String sql = "delete from role where id = ?";
    		Object[] args = {-1};
    		jdbcTemplate.update(sql, args);
    	}
    
    	private static void insertRole(JdbcTemplate jdbcTemplate) {
    		String sql = "insert into role(id, name, `desc`) values(?, ?, ?)";
    		Object[] args = {-1, "hehe", "  "};
    		jdbcTemplate.update(sql, args);
    	}
    }