软件环境: Eclipse + WebLogic 12c
1.在WebLogic中添加MySQL数据源,进入http://localhost:7001/console/,点击服务->数据源->新建。
2.在Eclipse中新建一个dynamic web project,编写entity bean。代码如下
package Entity;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="test")
public class user {
private int id;
private String name;
@Id
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;
}
}
@Entity:表明此类为entity bean
@Table(name="test"):与数据库中的表映射,并且表名为test。
3.编写一个servlet进行测试,代码如下
package Entity;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
/**
* Servlet implementation class TestEntityBean
*/
@WebServlet("/TestEntityBean")
public class TestEntityBean extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public TestEntityBean() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
Context ctx;
try {
ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup("MySQLDS"); //通过JNDI找到数据源
Connection conn = ds.getConnection(); //建立连接
Statement stmt = null;
ResultSet rs = null;
stmt = conn.createStatement();
String sql = "select * from test;";
rs = stmt.executeQuery(sql); //执行SQL
while(rs.next()){
rs.getInt("id");
rs.getString("name"); //获取查询结果
System.out.println(rs.getString("name"));
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
访问servlet,在控制台中打印出表中的值
该贴由koei123转至本版2015-6-2 8:56:16