Spring JPA 用法总结分析

不点 阅读:235 2021-03-31 17:19:46 评论:0

废话不多说,直接发送源码:

Repository 

package test.dao; 
 
import java.util.List; 
import java.util.Map; 
 
import org.springframework.jdbc.core.JdbcTemplate; 
 
import test.bean.User; 
import test.mapper.UserRowMapper; 
 
public class UserRepositoryImpl extends JdbcDaoSupport { 
 
	// create table 
	public void createTable() { 
		String sql = "create table test(name varchar(50), id bigint(20) NOT NULL AUTO_INCREMENT)"; 
		getJdbcTemplate().execute(sql); 
	} 
 
	// update insert delete 
	public void update() { 
		String sql = "update user set name = ? where id = ?"; 
		String name = "张胜鸿"; 
		int id = 100; 
		getJdbcTemplate().update(sql, new Object[] { name, id }); 
	} 
 
	// count(*) 
	public void count() { 
		String sql = "select count(1) from user"; 
		int count =getJdbcTemplate().queryForInt(sql); 
		System.out.println(count); 
	} 
 
	// select String 
	public void selectByString() { 
		String sql = "select name from user where id = ?"; 
		int id = 100; 
		String name = getJdbcTemplate().queryForObject(sql, 
				new Object[] { id }, java.lang.String.class); 
		System.out.println(name); 
	} 
 
	// select object 
	public void selectByObject() { 
		String sql = "select * from user where id = ?"; 
		int id = 100; 
		User user = getJdbcTemplate().queryForObject(sql, new Object[] { id }, 
				new UserRowMapper()); 
		System.out.println(user.getName()); 
	} 
 
	// select list 
	public void selectByList() { 
		String sql = "select * from user"; 
		List<User> list = getJdbcTemplate().query(sql, new UserRowMapper()); 
		for (User user : list) { 
			System.out.println(user.getId() + ";" + user.getName()); 
		} 
	} 
 
	// select row 
	@SuppressWarnings("unchecked") 
	public void selectByRows() { 
		String sql = "select * from user"; 
		List rows = getJdbcTemplate().queryForList(sql); 
		for (int i = 0; i < rows.size(); i++) { 
			Map map = (Map) rows.get(i); 
			System.out.println(map.get("name")); 
		} 
	} 
}

Mapper 

package test.mapper; 
 
import java.sql.ResultSet; 
import java.sql.SQLException; 
 
import org.springframework.jdbc.core.RowMapper; 
 
import test.bean.User; 
 
public class UserRowMapper implements RowMapper<User> { 
 
	public User mapRow(ResultSet rs, int index) throws SQLException { 
		User user = new User(); 
		user.setId(rs.getInt("id")); 
		user.setName(rs.getString("name")); 
		return user; 
	} 
 
}

Entity

package test.bean; 
 
public class User { 
	private int id; 
	private String name; 
 
	public int getId() { 
		return id; 
	} 
 
	public void setId(int id) { 
		this.id = id; 
	} 
 
	public String getName() { 
		return name; 
	} 
 
	public void setName(String name) { 
		this.name = name; 
	} 
}

注意:实列化UserRepositoryImpl  对象后,需要调用 setDataSource(dataSource); // 设定数据源,如果想知道是什么原因,需要查看JdbcDaoSupport  的源码:

声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

发表评论
搜索
KIKK导航

KIKK导航

排行榜
关注我们

一个IT知识分享的公众号