springboot_database
springboot1.5.7整合mybatis、jpa、redis、mongodb,對不同資料庫進行操作的例項
專案程式碼獲取:https://github.com/pysasuke/s…
專案結構
main
dao:資料庫互動層
- jpa:jpa與mysql資料庫互動類
public interface JpaUserRepository extends JpaRepository<JpaUser, Long> {
//jpa有預設實現類似findBy*(支援*And*)方法,其中*號為實體屬性名(名稱寫的不對會報錯哦)
JpaUser findByUsername(String username);
@Query("select count(u.id) from JpaUser u")
long count();
@Query("select u from JpaUser u where u.id=:id")
JpaUser findUserById(@Param("id") long id);
}
- mongo:mongodb資料庫互動類
public interface MongoUserRepository extends MongoRepository<MgUser, Long> {
//有預設實現類似findBy*(支援*And*)方法,其中*號為實體屬性名
MgUser findByNickname(String nickname);
//根據id為條件搜尋(預設實現的findOne方法是以mongodb中ObjectId為條件的)
MgUser findById(Long id);
}
- mybatis:mybatis與mysql資料庫互動類
//@Mapper(SpringbootDatabaseApplication類中使用了@MapperScan註解,故此處可以省略)
public interface TuserMapper {
int deleteByPrimaryKey(Long id);
int insert(Tuser record);
Tuser selectByPrimaryKey(Long id);
Tuser selectByUserName(String username);
int updateByPrimaryKeySelective(Tuser record);
}
entity:實體物件層
- jpa:jpa操作mysql相關實體物件
@Data
@Entity//標記這個類為資料庫表對映實體
@Table(name="user")//對應資料庫表名
public class JpaUser implements Serializable{
@Id//標記為主鍵
@GeneratedValue//標記主鍵自增
private Long id;
private String username;
private String password;
private String mobile;
private String email;
}
- mongo:mongodb相關實體物件
@Data
//需要與mongo中物件(文件)名一致
public class MgUser {
@Id
private ObjectId _id; //插入mongo時會自動生成_id,如果不加這個欄位則會把id屬性當成_id
@Field
private Long id;
private String nickname;
private String phone;
}
- mybatis:mybatis操作mysql相關實體物件
@Data
public class Tuser {
private Long id;
private String username;
private String password;
private String mobile;
private String email;
}
- redis:redis相關實體物件
//redisTemplate操作物件時物件需要實現序列化介面
@Data
public class Person implements Serializable{
private Long serialVersionUID=1L;
private Long id;
private String username;
private String password;
}
SpringbootDatabaseApplication:springboot啟動類
@SpringBootApplication
// mapper 介面類掃描包配置(可以省去dao層類上註解@Mapper)
@MapperScan("com.py.springboot_database.dao.mybatis")
public class SpringbootDatabaseApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootDatabaseApplication.class, args);
}
}
resources
- mapper:mybatis實體類對映檔案存放包
- application.properties:springboot配置檔案
## 資料來源配置
spring.datasource.url=jdbc:mysql://localhost:3306/springboot_database?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=py123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
## Mybatis 配置
##指向實體類包路徑
mybatis.typeAliasesPackage=com.py.springboot_database.entity.mybatis
##配置為 classpath 路徑下 mapper 包下,* 代表會掃描所有 xml 檔案
mybatis.mapperLocations=classpath:mapping/*.xml
## mongodb配置
spring.data.mongodb.uri=mongodb://localhost:27017/test
## Redis 配置
## Redis資料庫索引(預設為0)
spring.redis.database=0
## Redis伺服器地址
spring.redis.host=127.0.0.1
## Redis伺服器連線埠
spring.redis.port=6379
## Redis伺服器連線密碼(預設為空)
spring.redis.password=
## 連線池最大連線數(使用負值表示沒有限制)
spring.redis.pool.max-active=8
## 連線池最大阻塞等待時間(使用負值表示沒有限制)
spring.redis.pool.max-wait=-1
## 連線池中的最大空閒連線
spring.redis.pool.max-idle=8
## 連線池中的最小空閒連線
spring.redis.pool.min-idle=0
## 連線超時時間(毫秒)
spring.redis.timeout=0
test
- jpa:TestJpa類,jpa操作mysql物件增刪改查操作測試
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = SpringbootDatabaseApplication.class)
public class TestJpa {
@Autowired
private JpaUserRepository jpaUserRepository;
@Test
public void testInsert() {
long countBefore =jpaUserRepository.count();
JpaUser jpaUser = generateJpaUser();
jpaUserRepository.save(jpaUser);
long countAfter =jpaUserRepository.count();
Assert.assertEquals(++countBefore,countAfter);
}
@Test
public void testSelect() {
JpaUser jpaUser = generateJpaUser();
/*
插入成功後id會有值(mysql資料庫生成的)
前提是:
1.資料庫主鍵設定為自動增長
2.實體物件主鍵屬性上有註解@Id和@GeneratedValue
*/
jpaUserRepository.save(jpaUser);
JpaUser selectedJpaUser = jpaUserRepository.findOne(jpaUser.getId());
Assert.assertNotNull(selectedJpaUser);
Assert.assertEquals(jpaUser, selectedJpaUser);
}
@Test
public void testUpdate() {
JpaUser jpaUser = generateJpaUser();
jpaUserRepository.save(jpaUser);
JpaUser selectedJpaUser = jpaUserRepository.findOne(jpaUser.getId());
Assert.assertNotNull(selectedJpaUser);
selectedJpaUser.setPassword("654321");
//儲存修改後的物件,相當於update操作
jpaUserRepository.save(selectedJpaUser);
//findOne(預設實現)方法與findUserById(自己實現)都是根據id查詢
JpaUser updatedJpaUser = jpaUserRepository.findUserById(selectedJpaUser.getId());
Assert.assertNotNull(updatedJpaUser);
Assert.assertEquals(selectedJpaUser.getPassword(), updatedJpaUser.getPassword());
}
@Test
public void testDelete() {
JpaUser jpaUser = generateJpaUser();
jpaUserRepository.save(jpaUser);
jpaUserRepository.delete(jpaUser.getId());
JpaUser selectedJpaUser = jpaUserRepository.findUserById(jpaUser.getId());
Assert.assertNull(selectedJpaUser);
}
private JpaUser generateJpaUser() {
JpaUser jpaUser = new JpaUser();
jpaUser.setUsername("zhangsan");
jpaUser.setPassword("123456");
jpaUser.setMobile("13666666666");
jpaUser.setEmail("123456@qq.com");
return jpaUser;
}
}
- mongo:TestMongo類,mongodb測試
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = SpringbootDatabaseApplication.class)
public class TestMongo {
@Autowired
private MongoUserRepository userRepository;
@Test
public void test() {
MgUser mgUser = new MgUser();
mgUser.setId(1L);
mgUser.setNickname("pysasuke");
mgUser.setPhone("18650140605");
//插入成功後_id屬性有值(mongo資料庫生成的)
userRepository.insert(mgUser);
//該方法使用的是mongodb中ObjectId為條件的
// MgUser selectMgUser = userRepository.findOne(1L);
// MgUser selectMgUser = userRepository.findByNickname("pysasuke");
MgUser selectMgUser = userRepository.findById(1L);
Assert.assertEquals(mgUser.getId(), selectMgUser.getId());
}
}
- mybatis:TestMybatis類,mybatis操作mysql物件增刪改查測試
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = SpringbootDatabaseApplication.class)
public class TestMybatis {
@Autowired
private TuserMapper tuserMapper;
@Test
public void testInsert() {
Tuser tuser = generateTuser();
int row = tuserMapper.insert(tuser);
Assert.assertEquals(1, row);
}
@Test
public void testSelect() {
Tuser tuser = generateTuser();
/*
插入成功後id會有值(mysql資料庫生成的)
前提是:
1.主鍵設定為自動增長
2.xml中insert語句設定有:useGeneratedKeys="true" keyProperty="id"
*/
int row = tuserMapper.insert(tuser);
Assert.assertEquals(1, row);
Tuser selectedTuser = tuserMapper.selectByPrimaryKey(tuser.getId());
Assert.assertNotNull(selectedTuser);
Assert.assertEquals(tuser, selectedTuser);
}
@Test
public void testUpdate() {
Tuser tuser = generateTuser();
int row = tuserMapper.insert(tuser);
Assert.assertEquals(1, row);
Tuser selectedTuser = tuserMapper.selectByPrimaryKey(tuser.getId());
Assert.assertNotNull(selectedTuser);
selectedTuser.setPassword("654321");
tuserMapper.updateByPrimaryKeySelective(selectedTuser);
Tuser updatedTuser = tuserMapper.selectByPrimaryKey(selectedTuser.getId());
Assert.assertNotNull(updatedTuser);
Assert.assertEquals(selectedTuser.getPassword(), updatedTuser.getPassword());
}
@Test
public void testDelete() {
Tuser tuser = generateTuser();
int row = tuserMapper.insert(tuser);
Assert.assertEquals(1, row);
tuserMapper.deleteByPrimaryKey(tuser.getId());
Tuser selectedTuser = tuserMapper.selectByPrimaryKey(tuser.getId());
Assert.assertNull(selectedTuser);
}
private Tuser generateTuser() {
Tuser tuser = new Tuser();
tuser.setUsername("zhangsan");
tuser.setPassword("123456");
tuser.setMobile("13666666666");
tuser.setEmail("123456@qq.com");
return tuser;
}
}
- redis:TestRedis類,redis測試
/*
當redis資料庫裡面本來存的是字串資料或者要存取的資料就是字串型別資料的時候,
那麼使用StringRedisTemplate即可,
但是如果資料是複雜的物件型別,而取出的時候又不想做任何的資料轉換,直接從Redis裡面取出一個物件,
那麼使用RedisTemplate是更好的選擇。
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = SpringbootDatabaseApplication.class)
public class TestRedis {
//操作String
@Autowired
private StringRedisTemplate stringRedisTemplate;
//操作物件
@Autowired
private RedisTemplate redisTemplate;
@Test
public void testPutString() {
stringRedisTemplate.opsForValue().set("testPutString", "123456");
}
@Test
public void tesGetString() {
stringRedisTemplate.opsForValue().set("tesGetString", "123456");
String str = stringRedisTemplate.opsForValue().get("tesGetString");
Assert.assertEquals("123456", str);
//設定快取時間
stringRedisTemplate.opsForValue().set("tesGetString", "123456", 1000, TimeUnit.MILLISECONDS);//有效時間1s
try {
Thread.sleep(2000);//等待2s(等待設定為1s的時候後面可能取到值,redis的過期時間有延遲)
} catch (InterruptedException e) {
e.printStackTrace();
}
str = stringRedisTemplate.opsForValue().get("tesGetString");
Assert.assertNull(str);
}
//注意:redisTemplate操作物件時物件需要實現序列化介面
@Test
public void testObject() {
Person person = generatePerson();
redisTemplate.opsForValue().set("testObject:" + person.getUsername(), person, 600);
}
@Test
public void tesGetObject() {
Person person = generatePerson();
redisTemplate.opsForValue().set("tesGetObject:" + person.getUsername(), person);
Person cachePerson = (Person) redisTemplate.opsForValue().get("tesGetObject:" + person.getUsername());
Assert.assertEquals(person, cachePerson);
}
@Test
public void tesDeleteCache() {
stringRedisTemplate.opsForValue().set("tesDeleteCache", "123456");
String cacheStr = stringRedisTemplate.opsForValue().get("tesDeleteCache");
Assert.assertEquals("123456", cacheStr);
stringRedisTemplate.delete("tesDeleteCache");
String DeleteStr = stringRedisTemplate.opsForValue().get("tesDeleteCache");
Assert.assertNull(DeleteStr);
}
//兩者操作互不影響
@Test
public void testStrRedisTempAndRedisTemp(){
Person person = generatePerson();
//生成key為:xACxEDx00x05tx00x04test
redisTemplate.opsForValue().set("testDiff", person);
//生稱key為:test
stringRedisTemplate.opsForValue().set("testDiff", "123456");
String cacheStr = stringRedisTemplate.opsForValue().get("testDiff");
Assert.assertEquals("123456", cacheStr);
Person cachePerson = (Person) redisTemplate.opsForValue().get("testDiff");
Assert.assertEquals(person, cachePerson);
}
private Person generatePerson() {
Person person = new Person();
person.setId(1L);
person.setUsername("wangwu");
person.setPassword("123456");
return person;
}
}
deploy
- update.sql:資料庫sql檔案
CREATE DATABASE springboot_database;
USE springboot_database;
DROP TABLE IF EXISTS `user` ;
CREATE TABLE `user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`username` varchar(50) NOT NULL,
`password` varchar(50) NOT NULL,
`mobile` varchar(20) NOT NULL,
`email` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- lombok相關start -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- lombok相關end -->
<!-- mongodb相關start -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<!-- mongodb相關end -->
<!-- redis相關start -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
<version>1.4.7.RELEASE</version>
</dependency>
<!-- redis相關end -->
<!-- mybatis相關start -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<!-- mybatis相關end -->
<!-- mysql相關start -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- mysql相關end -->
<!-- jpa相關start -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- jpa相關end -->
</dependencies>