日期:2014-05-16 浏览次数:20515 次
package org.ourpioneer.vehicle.util; import org.hsqldb.Server; /** * 启动HSQL服务器实例 * * @author Nanlei * */ public class HsqlServer { private void startHsqlServer(String dbPath, String dbName, int port) { Server server = new Server(); // 0表示第0个数据库,Server模式可以启动10个数据库 server.setDatabasePath(0, dbPath + dbName); server.setDatabaseName(0, dbName); server.setPort(port); server.setSilent(true); server.start(); System.out.println("HSQLDB Server started!"); } public static void main(String[] args) { // 源代码路径 System.out.println(System.getProperty("user.dir")); // 类路径 System.out.println(Thread.currentThread().getContextClassLoader() .getResource(".").getPath()); String base = System.getProperty("user.dir"); String dbPath = base + "\\src\\main\\resources\\org\\ourpioneer\\vehicle\\db\\"; String dbName = "vehicle"; int port = 2011; new HsqlServer().startHsqlServer(dbPath, dbName, port); } }
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="org.hsqldb.jdbcDriver" /> <property name="url" value="jdbc:hsqldb:hsql://localhost:2011/vehicle;shutdown=true" /> <property name="username" value="ROOT" /> <property name="password" value="123" /> </bean>
package org.ourpioneer.vehicle.dao; import org.ourpioneer.vehicle.bean.Vehicle; /** * VehicleDAO:封装数据操作方法 * * @author Nanlei * */ public interface VehicleDAO { public void insert(Vehicle vehicle); public void update(Vehicle vehicle); public void delete(Vehicle vehicle); public Vehicle findById(int id); }
package org.ourpioneer.vehicle.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.sql.DataSource; import org.ourpioneer.vehicle.bean.Vehicle; /** * VehicleDAO实现类 * * @author Nanlei * */ public class VehicleDAOImpl implements VehicleDAO { private DataSource dataSource; /** * 注入数据源 * * @param dataSource */ public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } public Vehicle findById(int id) { String sql = "select * from vehicle where ID=?"; Connection conn = null; Vehicle vehicle = null; try { conn = dataSource.getConnection(); PreparedStatement pstat = conn.prepareStatement(sql); pstat.setInt(1, id); ResultSet rs = pstat.executeQuery(); if (rs.next()) { vehicle = new Vehicle(rs.getString("PLATE"), rs .getString("CHASSIS"), rs.getString("COLOR"), rs .getInt("WHEEL"), rs.getInt("SEAT")); vehicle.setId(rs.getInt("ID")); } rs.close(); pstat.close(); } catch (SQLException e) { e.printStackTrace(); } finally { if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } return vehicle; } /** * 添加Vehicle */ public void insert(Vehicle vehicle) { String sql = "insert into vehicle(PLATE,CHASSIS,COLOR,WH