本文描述的是通过spring框架实现数据持久化操作,具体内容如下:
1,POJO类定义:
1 import java.io.Serializable; 2 import java.util.Date; 3 4 public class User implements Serializable{ 5 private int userId; 6 7 private String userName; 8 9 private String password; 10 11 private int credits; 12 13 private String lastIp; 14 15 private Date lastVisit; 16 17 public String getLastIp() { 18 return lastIp; 19 } 20 21 public void setLastIp(String lastIp) { 22 this.lastIp = lastIp; 23 } 24 25 public Date getLastVisit() { 26 return lastVisit; 27 } 28 29 public void setLastVisit(Date lastVisit) { 30 this.lastVisit = lastVisit; 31 } 32 33 public int getUserId() { 34 return userId; 35 } 36 37 public void setUserId(int userId) { 38 this.userId = userId; 39 } 40 41 public String getUserName() { 42 return userName; 43 } 44 45 public void setUserName(String userName) { 46 this.userName = userName; 47 } 48 49 public String getPassword() { 50 return password; 51 } 52 53 public void setPassword(String password) { 54 this.password = password; 55 } 56 57 public int getCredits() { 58 return credits; 59 } 60 61 public void setCredits(int credits) { 62 this.credits = credits; 63 } 64 }
2,数据访问层定义:
import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowCallbackHandler; import org.springframework.stereotype.Repository; @Repository public class UserDao { @Autowired private JdbcTemplate jdbcTemplate; public int getMatchCount(String userName, String password) { String sqlStr = " SELECT count(*) FROM t_user " + " WHERE user_name =? and password=? "; // return jdbcTemplate.queryForInt(sqlStr, new Object[] { userName, password }); return jdbcTemplate.queryForObject(sqlStr, new Object[] { userName, password },Integer.class); } public User findUserByUserName(final String userName) { String sqlStr = " SELECT user_id,user_name,credits " + " FROM t_user WHERE user_name =? "; final User user = new User(); jdbcTemplate.query(sqlStr, new Object[] { userName }, new RowCallbackHandler() { public void processRow(ResultSet rs) throws SQLException { user.setUserId(rs.getInt("user_id")); user.setUserName(userName); user.setCredits(rs.getInt("credits")); } }); return user; } public void updateLoginInfo(User user) { String sqlStr = " UPDATE t_user SET last_visit=?,last_ip=?,credits=? " + " WHERE user_id =?"; jdbcTemplate.update(sqlStr, new Object[] { user.getLastVisit(), user.getLastIp(),user.getCredits(),user.getUserId()}); } public void insertUserInfo() { String sqlStr = "insert into t_user(user_name,password)" + "values(‘liushaocun‘,‘405424‘)"; jdbcTemplate.execute(sqlStr); } }
3,spring配置文件applicationContext.xml:
<?xml version="1.0" encoding="UTF-8" ?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <!-- 扫描类包,将标注Spring注解的类自动转化Bean,同时完成Bean的注入 --> <context:component-scan base-package="com.lsc.SpringJDBC"/> <!-- 配置数据源 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" p:driverClassName="com.mysql.jdbc.Driver" p:url="jdbc:mysql://localhost:3306/sampledb" p:username="root" p:password="405424" /> <!-- 配置Jdbc模板 --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" p:dataSource-ref="dataSource" /> <bean id="userDao" class="com.lsc.SpringJDBC.UserDao"/> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" p:dataSource-ref="dataSource" /> <!-- 通过AOP配置提供事务增强,让service包下所有Bean的所有方法拥有事务 --> <aop:config proxy-target-class="true"> <aop:pointcut id="serviceMethod" expression=" execution(* com.lsc.SpringJDBC..*(..))" /> <aop:advisor pointcut-ref="serviceMethod" advice-ref="txAdvice" /> </aop:config> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="*" /> </tx:attributes> </tx:advice> </beans>
4,spring的依赖文件pom:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.lsc</groupId> <artifactId>SpringJDBC</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>SpringJDBC</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>3.2.4.RELEASE</version> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.2.2</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>3.2.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>3.2.4.RELEASE</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.8.5</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.6</version> </dependency> </dependencies> </project>
5,数据库相关操作:
create database "sampledb"; DROP TABLE IF EXISTS `t_login_log`; CREATE TABLE `t_login_log` ( `login_log_id` int(100) NOT NULL, `user_id` int(100) DEFAULT NULL, `ip` varchar(23) DEFAULT NULL, `login_datetime` datetime DEFAULT NULL, PRIMARY KEY (`login_log_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of t_login_log -- ---------------------------- -- ---------------------------- -- Table structure for t_user -- ---------------------------- DROP TABLE IF EXISTS `t_user`; CREATE TABLE `t_user` ( `user_id` int(100) DEFAULT NULL, `user_name` varchar(30) DEFAULT NULL, `credits` int(100) DEFAULT NULL, `password` varchar(32) DEFAULT NULL, `last_visit` datetime DEFAULT NULL, `last_ip` varchar(23) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
6,测试程序:
import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Hello world! * */ public class App { public static void main(String[] args) { ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml"); UserDao dao = (UserDao) app.getBean("userDao"); dao.insertUserInfo(); } }
时间: 2024-12-25 08:03:10