JdbcTemplateデータベースをオブジェクトで操作

2628 ワード

1.インタフェースと実装クラスの作成
//PersonDao  
package com.entity;

public interface PersonDao {
public Person find(int id);
}

//PersonDao   PersonDaoImpl
package com.entity;

import java.sql.*;

import javax.sql.DataSource;

public class PersonDaoImpl implements PersonDao {
private DataSource dataSource;

/**
 *     
 */
public Person find(int id) {
Connection con=null;
PreparedStatement ps=null;
ResultSet rs=null;
try{
con=dataSource.getConnection();
ps=con.prepareStatement("select * from person where id=?");
ps.setInt(1, id);
rs=ps.executeQuery();
Person p=new Person();
if(rs.next()){
p.setId(rs.getInt("id"));
p.setName(rs.getString("name"));
p.setPassword(rs.getString("password"));
}
return p;
}catch(SQLException e){
e.printStackTrace();
}finally{
try {
if(rs!=null){
rs.close();
} 
if(ps!=null){
ps.close();
}
if(con!=null){
con.close();
}
}catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
/**
 * Spring        setDataSource  ,        Bean 
 * @param dataSource
 */
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}

public DataSource getDataSource() {
return dataSource;
}

}

//     
package com.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.entity.Hello;
import com.entity.IHello;
import com.entity.IHello2;
import com.entity.IHelloHandler;
import com.entity.Person;
import com.entity.PersonDao;

public class test1 {

/**
 * @param args
 */
public static void main(String[] args) {
try {
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
PersonDao personDao=(PersonDao) context.getBean("personDao");
Person p=personDao.find(1);
System.out.println("  :"+p.getName()+",  :"+p.getPassword());
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

2.プロファイルの変更



oracle.jdbc.driver.OracleDriver


jdbc:oracle:thin:@192.168.1.32:1521:orcl


usera


usera






3.データベースに対応するテーブルを作成する
4.運転結果