0
我有用户类包含了像如何在Spring MVC中将数据从bean插入数据库?
user.java
@Table(name="user");
@Column(name="userid")
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}//setter and getter for username,password and mobile no.
我在注册页面的用户数据,其中我进入的一些细节上面,成功登录任何响应后即时得到一遍存储到该用户对象,但现在我想将它插入到database。这是我的
userdao.java
package com.xyz.dao;
import com.xyz.model.User;
public class UserDao {
public interface UserDAO {
public void insert(User user);
}
}
,这是我
import com.xyz.dao.UserDao.UserDAO;
import com.xyz.model.User;
public class UserJdbcImpl implements UserDAO {
private static final String DB_DRIVER = "com.mysql.jdbc.Driver";
private static final String DB_CONNECTION = "jdbc:mysql://localhost:3306/user";
private static final String DB_USER = "root";
private static final String DB_PASSWORD = "root";
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public void insert(User user) {
Connection conn = null;
PreparedStatement preparedStatement = null;
String sql = "INSERT INTO user " +
"(userMobile,userEmail) VALUES (?, ?)";
try {
conn = getDBConnection();
preparedStatement = conn.prepareStatement(sql);
//conn = dataSource.getConnection();
System.out.println("connecting..");
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, user.getUserMobile());
ps.setString(2, user.getUserEmail());
ps.executeUpdate();
ps.close();
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
System.out.println("connection failed");
}
}
}
}
private static Connection getDBConnection() {
Connection conn = null;
try {
Class.forName(DB_DRIVER);
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
try {
conn = DriverManager.getConnection(DB_CONNECTION, DB_USER,DB_PASSWORD);
return conn;
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return conn;
}
}
正如我要去进行验证的登录页面我使用的弹簧security.xml文件,这是我的春天db.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/user" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
</beans>
运行后,没有数据被插入到数据库中。任何帮助,我做错了吗?
为什么不使用Spring Data? – chrylis 2014-09-12 11:39:59
@chrylis我无法找到错误..我只插入弹簧数据只有 – ghhhhhhhh 2014-09-12 11:41:49
什么是主键?它的发电策略是什么? – zerocool 2014-09-12 11:52:14