日期:2014-05-16 浏览次数:20872 次
create table user ( id int NOT NULL primary key auto_increment, name varchar(20) NOT NULL, age int NOT NULL );
insert into user (name, age) values ("name1", 11)
package com.xx.test.dao; import java.io.Serializable; public class User implements Serializable { private static final long serialVersionUID = -433577178466098132L; private int id; private String name; private int age; 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; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
package com.xx.test.dao; import java.util.List; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; public interface UserMapper { @Insert("INSERT into user (name, age) VALUES (#{name}, #{age})") public void insertUser(User user); @Select("SELECT * from user WHERE id = #{id}") public User getUser(@Param("id") int id); @Select("SELECT * from user") public List<User> getAllUser(); }
<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/mytest" /> <property name="username" value="root" /> <property name="password" value="admin" /> </bean> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> </bean> <!-- mapper bean --> <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> <property name="mapperInterface" value="com.xx.test.dao.UserMapper" /> <property name="sqlSessionFactory" ref="sqlSessionFactory" /> </bean>
<servlet> <servlet-name>appServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/spring/appServlet/servlet-context.xml, /WEB-INF/classes/mybatis-context.xml, </param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet>
<!-- mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.1.1</version> </dependency> <!-- mysql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.21</version> </dependency>
List<User> users = userMapper.getAllUser(); for(User u : users)