酷代码 AI
菜单
服务商

Spring框架实战:从配置到实现,搞定员工信息查询功能

1、创建spring xml配置文件,例如 applicationContext.xml: ```xml <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd"> <!-- 导入外部数据文件db.properties --> <context:property-placeholder location="classpath:db.properties"/> <!-- 配置数据源 drivermangerdatasource --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${db.driver}"/> <property name="url" value="${db.url}"/> <property name="username" value="${db.username}"/> <property name="password" value="${db.password}"/> </bean> <!-- 配置 jdbctemplate --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="dataSource"/> </bean> </beans> ``` 2、创建empdao接口的实现类 EmpDaoImpl,完成 selectbyld(int id) 的功能: ```java package cn.hnzj.spring.dao; import cn.hnzj.spring.pojo.Employee; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Repository; import java.sql.ResultSet; import java.sql.SQLException; @Repository public class EmpDaoImpl implements EmpDao { @Autowired private JdbcTemplate jdbcTemplate; @Override public Employee selectById(int id) { String sql = "SELECT * FROM employee WHERE empld = ?"; return jdbcTemplate.queryForObject(sql, new EmployeeMapper(), id); } private static final class EmployeeMapper implements RowMapper<Employee> { @Override public Employee mapRow(ResultSet resultSet, int i) throws SQLException { Employee employee = new Employee(); employee.setEmpld(resultSet.getInt("empld")); employee.setEmpname(resultSet.getString("empname")); employee.setEmpage(resultSet.getInt("empage")); return employee; } } } ``` 3、创建empservice接口的实现类 EmpServiceImpl,完成 findbyld(int id) 的功能: ```java package cn.hnzj.spring.service; import cn.hnzj.spring.dao.EmpDao; import cn.hnzj.spring.pojo.Employee; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class EmpServiceImpl implements EmpService { @Autowired private EmpDao empDao; @Override public Employee findById(int id) { return empDao.selectById(id); } } ``` 以上就完成了使用Spring框架的配置和实现类的编写。 ######[AI写代码神器 | 2135点数解答 | 2024-06-12 08:32:35]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]