14、JDBCに基づくBaseDaoの実現
1、jdbc.propertiesのプロファイルは次のとおりです.
2、BaseDao.java
3、BaseDaoImpl.java
4、DButils.java
5、UserDao.java
6、UserDaoImpl.java
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost/bjsxteasyui
username=root
password=root
2、BaseDao.java
public interface BaseDao<Entity> {
void save(Entity obj) throws Exception ;
void update (Entity obj) throws Exception;
void delete(int id) throws Exception;
List<Entity> findAll() throws Exception;
Entity findById( int id) throws Exception;
}
3、BaseDaoImpl.java
/**
* jdbc : 1 2 sql 3 preparedstatemenet
*
* @param <Entity>
*/
public class BaseDaoImpl<Entity> implements BaseDao<Entity>{
//public
protected Class clazz ;
public BaseDaoImpl(){
//System.out.println(this.getClass());
ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
//
clazz = (Class)pt.getActualTypeArguments()[0];
System.out.println(clazz);
}
/**
*
*/
public void save(Entity obj) throws Exception {
//obj.getSimpleName();
Connection conn = DBUtils.createConn();
String sql = "insert into " + clazz.getSimpleName() + " values(null ";
//
Field[] fs = clazz.getDeclaredFields();
//System.out.println(fs.length);
for (int i = 1; i < fs.length; i++) {
sql += ",? " ;
}
sql = sql + ")";
System.out.println(sql);
//
PreparedStatement ps = DBUtils.getPs(conn, sql);
//ps.setString(1, user.getName());
for (int i = 1; i < fs.length; i++) {
//
String MethodName = "get" +Character.toUpperCase(fs[i].getName().charAt(0)) + fs[i].getName().substring(1) ;
Method m = clazz.getMethod(MethodName);
ps.setObject(i, m.invoke(obj));
}
ps.executeUpdate();
DBUtils.close(ps);
DBUtils.close(conn);
}
/**
*
*/
public void update(Entity obj) throws Exception {
Connection conn = DBUtils.createConn();
// update user set name = ? , age = ? where id = ?
String sql = " update " + clazz.getSimpleName() + " set ";
Field[] fs = clazz.getDeclaredFields();
for (int i = 1; i < fs.length; i++) {
sql += fs[i].getName() + "=?,";
}
sql = sql.substring(0, sql.length()-1) + " where id = ? ";
PreparedStatement ps = DBUtils.getPs(conn, sql);
for (int i = 1; i < fs.length; i++) {
String methodName = "get" + Character.toUpperCase(fs[i].getName().charAt(0)) + fs[i].getName().substring(1);
Method m = clazz.getMethod(methodName);
ps.setObject(i, m.invoke(obj));// user.getName();
}
Method m2 = clazz.getMethod("getId");
ps.setInt(fs.length,(Integer)m2.invoke(obj));
ps.executeUpdate();
DBUtils.close(ps);
DBUtils.close(conn);
}
/**
* id
*/
public Entity findById(int id) throws Exception {
Connection conn = DBUtils.createConn();
String sql = " select * from " + clazz.getSimpleName() + " where id = " + id ;
PreparedStatement ps = DBUtils.getPs(conn, sql);
ResultSet rs = ps.executeQuery();
Entity entity = (Entity) clazz.newInstance();
if(rs.next()){
Field[] fs = clazz.getDeclaredFields();
for (int i = 0; i < fs.length; i++) {
String methodName = "set" + Character.toUpperCase(fs[i].getName().charAt(0)) + fs[i].getName().substring(1);
Method m = clazz.getDeclaredMethod(methodName, fs[i].getType());
m.invoke(entity, rs.getObject(fs[i].getName()));
}
}
DBUtils.close(rs);
DBUtils.close(ps);
DBUtils.close(conn);
return entity;
}
/**
*
*/
public List<Entity> findAll() throws Exception {
Connection conn = DBUtils.createConn();
String sql =" select * from " + clazz.getSimpleName();
PreparedStatement ps = DBUtils.getPs(conn, sql);
List<Entity> list = new ArrayList<Entity>();
ResultSet rs = ps.executeQuery();
while(rs.next()){
Entity entity = (Entity)clazz.newInstance();
Field[] fs = clazz.getDeclaredFields();
for (int i = 0; i < fs.length; i++) {
String methodName = "set"+ Character.toUpperCase(fs[i].getName().charAt(0)) + fs[i].getName().substring(1);
Method m = clazz.getMethod(methodName, fs[i].getType());
m.invoke(entity, rs.getObject(fs[i].getName()));
}
list.add(entity);
}
DBUtils.close(rs);
DBUtils.close(ps);
DBUtils.close(conn);
return list;
}
/**
*
*/
public void delete(int id) throws Exception {
Connection conn = DBUtils.createConn();
String sql = " delete from " + clazz.getSimpleName() + " where id =" +id;
PreparedStatement ps = DBUtils.getPs(conn, sql);
ps.executeUpdate(sql);
DBUtils.close(ps);
DBUtils.close(conn);
}
/**
*
* @param sql
* @param params
* @return
*/
public List<Entity> queryListForParams(String sql,Object[] params ) throws Exception{
Connection conn = DBUtils.createConn();
PreparedStatement ps = null;
ResultSet rs = null;
List list = new ArrayList();
try {
// statement ( sql)
ps = conn.prepareStatement(sql); // select * from org where id = ? and name = ? [1 , z3]
if(params!=null){
for(int i=0;i<params.length;i++){
ps.setObject(i+1, params[i]);
}
}
Field[] fs = clazz.getDeclaredFields();
rs = ps.executeQuery();
while(rs.next()){
Object obj = clazz.getConstructor().newInstance();
for(int i = 0 ; i <fs.length;i++ ){
String methodName = "set" +fs[i].getName().substring(0, 1).toUpperCase()+fs[i].getName().substring(1);
Method m = clazz.getMethod(methodName, fs[i].getType());
Object value = rs.getObject(fs[i].getName());
m.invoke(obj, value);
}
list.add(obj);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
DBUtils.close(rs);
DBUtils.close(ps);
DBUtils.close(conn);
}
return list;
}
}
4、DButils.java
public class DBUtils {
private static Properties props = new Properties();
static{
InputStream is = null;
is = DBUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
try {
props.load(is);
} catch (IOException e) {
e.printStackTrace();
} finally{
if(is!=null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//
public static Connection createConn(){
Connection conn = null;
try {
Class.forName((String)props.get("driver"));
//ip +
conn = DriverManager.getConnection((String)props.get("url"), (String)props.get("username"), (String)props.get("password"));
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
//
public static PreparedStatement getPs(Connection conn , String sql){
PreparedStatement ps = null;
try {
ps = conn.prepareStatement(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return ps ;
}
public static void close(Connection conn){
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(ResultSet rs){
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(PreparedStatement ps){
if(ps != null){
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
5、UserDao.java
public interface UserDao extends BaseDao<<span style="font-family: Arial, Helvetica, sans-serif;">User</span><span style="font-family: Arial, Helvetica, sans-serif;">> {</span>
}
6、UserDaoImpl.java
public class UserDaoImpl extends BaseDaoImpl<User> implements UserDao {
//
}