怎么开彩票网站做站长,自己搭建网站需要什么,网站建设营销,网站seo 文章转载 修改标题一#xff0c;JPA相关的常用注解和对象
Entity#xff0c;用于实体类声明语句之前#xff0c;指出该Java类为实体类#xff0c;将映射到指定的数据库表#xff1b;Table#xff0c;当实体类与其映射的数据库表名不同名时需要使用。该标注与Entity标注并列使用JPA相关的常用注解和对象
Entity用于实体类声明语句之前指出该Java类为实体类将映射到指定的数据库表Table当实体类与其映射的数据库表名不同名时需要使用。该标注与Entity标注并列使用
置于实体类声明语句之前用于指明数据库的表名。此外Table标注还有catalog和schema选项
用于设置表所属的数据库目录或模式通常为数据库名Basic用于属性到表字段的映射。如果get方法前没加注解默认是该注解。fetch属性
表示该属性的读取策略EAGER表示主支抓取LAZY表示延迟加载。
optional属性表示该属性是否允许为空默认值为true。Id用于将实体类的属性映射为主键
GeneratedValue(strategy GenerationType.SEQUENCE, generator xx_seq)指定主键生成策略,参见GenerationType 枚举类
SequenceGenerator(name xx_seq, sequenceName xx_seq)
Column(namexxx)位于属性前或get方法前通常用于属性名与映射的表列名不同时
name属性可以指定表名还有unique、nullable、length等属性指定表列的属性Transient表示当前类属性无需映射到数据库表中字段Temproal主要针对 Date 类型的属性使用可以通过该注解指定时间的精度有
三种精确度DATETIMETIMESTAMP三种精确度DATETIMETIMESTAMP
分别表示精确到日期精确到时分秒精确到日期时分秒EntityManagerFactory类似与 hibernate 的 SessionFactoryEntityManager是JPA中用于增删改查的接口它充当了内存中的Java对象和数据库数据存储之间的桥梁EntityTransactionJPA事务处理相关根据EntityManager对象建立二SpringBoot接入JPA连接H2或MySQL例子
1首先在pom.xml中添加Spring Data JPA和数据库驱动的依赖
dependencies!-- Spring Boot Starter Data JPA --dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-data-jpa/artifactId/dependency!-- 数据库驱动以H2数据库为例 --dependencygroupIdcom.h2database/groupIdartifactIdh2/artifactIdscoperuntime/scope/dependency
/dependencies
!-- 其它依赖省略 --
2然后在 application.properties 或 application.yml 中配置数据库连接和JPA属性
# application.properties
spring.datasource.urljdbc:h2:mem:testdb
spring.datasource.driverClassNameorg.h2.Driver
#下面两行是连接mysql数据库
#spring.datasource.urljdbc:mysql://localhost:3306/mydb?useSSLfalse
#spring.datasource.driver-class-namecom.mysql.cj.jdbc.Driver
spring.datasource.usernamesa
spring.datasource.passwordspring.jpa.database-platformorg.hibernate.dialect.H2Dialect# 下面一行是使用mysql数据库
#spring.jpa.database-platformorg.hibernate.dialect.MySQL5InnoDBDialect#下面一行表示每次运行应用程序时更新数据库模式
#即会根据java实体类相应字段的变化情况更新DB中相关表的字段
#值除了update外还有create,但推荐使用 update,因create会删除对应表然后再新创建表
spring.jpa.hibernate.ddl-autoupdate#下面一行表示在控制台中显示执行的SQL语句
spring.jpa.show-sqltrue
3创建一个实体类User
import javax.persistence.*;Entity
public class User {IdGeneratedValue(strategy GenerationType.IDENTITY)private Long id;Column(nullable false)private String name;Column(nullable false)private Integer age;// 更多字段增加标准的getter和setter方法省略
}4创建一个继承自JpaRepository的接口UserRepository
import org.springframework.data.jpa.repository.JpaRepository;Repository
public interface UserRepository extends JpaRepositoryUser, Long {/** 根据名字进行模糊查询返回对象结果列表其中 ?1 代表传递给查询方法的第一个参数*/Query(SELECT u FROM User u WHERE u.name LIKE %?1%)ListUser findByUserName(String text);/** 根据名字和年龄查找, 其中 :xxx 和 注解Param(xxx)中指定的名称要对应上nativeQuerytrue, 表示采用原生SQL语句方式编写查询*/Query(nativeQuerytrue, valueselect * from user where name :uname and age :uage)ListUser queryByCondition(Param(uname) String uname, Param(uage) Integer uage);}5创建一个服务类UserService
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;Service
public class UserService {Autowiredprivate UserRepository userRepository;PersistenceUnitprivate EntityManagerFactory entityManagerFactory;// 查询public ListUser listAllUsers() {return userRepository.findAll();}// 模糊查询public ListUser findByUserName(String userName) {return userRepository.findByUserName(userName);}// 精确查询public User getUserById(Long id) {return userRepository.findById(id).orElse(null);}// 保存(新增或更新)public User saveUser(User user) {return userRepository.save(user);}// 精确删除public void deleteEntity(Long userId) {EntityManager entityManager entityManagerFactory.createEntityManager();EntityTransaction transaction null;try {// 开启事务transaction entityManager.getTransaction();transaction.begin();// 通过ID查询到实体User entityToDelete entityManager.find(User.class, id);// 删除实体entityManager.remove(entityToDelete);// 提交事务transaction.commit(); } catch(Exception e) {if (transaction ! null transaction.isActive()) {transaction.rollback();}// 处理异常e.printStackTrace();} finally {entityManager.close();}}//精确批量删除public void deleteEntity(Class? entityClass, String fieldName, List? fieldValues) {EntityManager entityManager entityManagerFactory.createEntityManager();EntityTransaction transaction null;try {// 开启事务transaction entityManager.getTransaction();transaction.begin();Query query entityManager.createQuery(delete from entityClass.getSimpleName() e where e. fieldName in :fieldValues);query.setParameter(fieldValues, fieldValues);int delNum query.executeUpdate();// 提交事务transaction.commit();} catch(Exception e) {if (transaction ! null transaction.isActive()) {transaction.rollback();}// 处理异常e.printStackTrace();} finally {entityManager.close();} } }6controller 层省略
RestController
RequestMapping(/user)
public class UserController {Autowiredprivate UserService userService;/** 通过用户名称查询用户列表 */GetMapping(/query)public ListUser queryUser(RequestParam(name) String name){ListUser users userService.findByUserName(name);return users;}}
7最后创建一个启动类SpringBootJpaApplication
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;SpringBootApplication
public class SpringBootJpaApplication {public static void main(String[] args) {SpringApplication.run(SpringBootJpaApplication.class, args);}
}8部分单元测试对应的包名相应修改
import com.xx.yy.kk.dao.UserRepository;
import com.xx.yy.kk.model.User;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;import java.util.Optional;RunWith(SpringRunner.class)
SpringBootTest
public class UserTest {Autowiredprivate UserRepository userRepository;Beforepublic void before() {User user new User();user.setId(1L);user.setName(张三); userRepository.save(user);user new User();user.setId(3L);user.setName(李四); userRepository.save(user);user.setId(5L);user.setName(王五); userRepository.save(user);}Testpublic void testAdd() {User user new User();user.setId(2L);user.setName(老六); userRepository.save(user);User new User();user.setId(4L);user.setName(王七); userRepository.save(user);}Testpublic void testQuery() {String userName张三;ListUser users userRepository.findByUserName(zhangsan);//...more...}Afterpublic void after() {userRepository.deleteById(1L);userRepository.deleteById(3L);userRepository.deleteById(5L);}}
部分代码需要补全或结合自己的情况修改这里仅展示SpringBoot接入JPA连接数据库H2或MySQL例子的过程谢谢拍砖讨论... 文章转载自: http://www.morning.gfprf.cn.gov.cn.gfprf.cn http://www.morning.qpmmg.cn.gov.cn.qpmmg.cn http://www.morning.wqpr.cn.gov.cn.wqpr.cn http://www.morning.spxsm.cn.gov.cn.spxsm.cn http://www.morning.rlfr.cn.gov.cn.rlfr.cn http://www.morning.jqkrt.cn.gov.cn.jqkrt.cn http://www.morning.mjxgs.cn.gov.cn.mjxgs.cn http://www.morning.kmcfw.cn.gov.cn.kmcfw.cn http://www.morning.ysqb.cn.gov.cn.ysqb.cn http://www.morning.svtxeu.com.gov.cn.svtxeu.com http://www.morning.hknk.cn.gov.cn.hknk.cn http://www.morning.mnnxt.cn.gov.cn.mnnxt.cn http://www.morning.ypqwm.cn.gov.cn.ypqwm.cn http://www.morning.mnkhk.cn.gov.cn.mnkhk.cn http://www.morning.nzmw.cn.gov.cn.nzmw.cn http://www.morning.4r5w91.cn.gov.cn.4r5w91.cn http://www.morning.kybyf.cn.gov.cn.kybyf.cn http://www.morning.nhrkc.cn.gov.cn.nhrkc.cn http://www.morning.yfnjk.cn.gov.cn.yfnjk.cn http://www.morning.qfnrx.cn.gov.cn.qfnrx.cn http://www.morning.pqkrh.cn.gov.cn.pqkrh.cn http://www.morning.xckqs.cn.gov.cn.xckqs.cn http://www.morning.mhlsx.cn.gov.cn.mhlsx.cn http://www.morning.ywxln.cn.gov.cn.ywxln.cn http://www.morning.bqyb.cn.gov.cn.bqyb.cn http://www.morning.npxcc.cn.gov.cn.npxcc.cn http://www.morning.rycbz.cn.gov.cn.rycbz.cn http://www.morning.cpwmj.cn.gov.cn.cpwmj.cn http://www.morning.xzgbj.cn.gov.cn.xzgbj.cn http://www.morning.thwcg.cn.gov.cn.thwcg.cn http://www.morning.ynstj.cn.gov.cn.ynstj.cn http://www.morning.mqnbm.cn.gov.cn.mqnbm.cn http://www.morning.tjwfk.cn.gov.cn.tjwfk.cn http://www.morning.lhrcr.cn.gov.cn.lhrcr.cn http://www.morning.bpkqd.cn.gov.cn.bpkqd.cn http://www.morning.hzryl.cn.gov.cn.hzryl.cn http://www.morning.nlgyq.cn.gov.cn.nlgyq.cn http://www.morning.dfwkn.cn.gov.cn.dfwkn.cn http://www.morning.bnlsd.cn.gov.cn.bnlsd.cn http://www.morning.rstrc.cn.gov.cn.rstrc.cn http://www.morning.bmsqq.cn.gov.cn.bmsqq.cn http://www.morning.gnjtg.cn.gov.cn.gnjtg.cn http://www.morning.gwxsk.cn.gov.cn.gwxsk.cn http://www.morning.kbyp.cn.gov.cn.kbyp.cn http://www.morning.frcxx.cn.gov.cn.frcxx.cn http://www.morning.sjqpm.cn.gov.cn.sjqpm.cn http://www.morning.kfcz.cn.gov.cn.kfcz.cn http://www.morning.pjfmq.cn.gov.cn.pjfmq.cn http://www.morning.wknbc.cn.gov.cn.wknbc.cn http://www.morning.mqdr.cn.gov.cn.mqdr.cn http://www.morning.pbgnx.cn.gov.cn.pbgnx.cn http://www.morning.kngqd.cn.gov.cn.kngqd.cn http://www.morning.qzsmz.cn.gov.cn.qzsmz.cn http://www.morning.cryb.cn.gov.cn.cryb.cn http://www.morning.sqxr.cn.gov.cn.sqxr.cn http://www.morning.hrypl.cn.gov.cn.hrypl.cn http://www.morning.yhdqq.cn.gov.cn.yhdqq.cn http://www.morning.trkl.cn.gov.cn.trkl.cn http://www.morning.mjxgs.cn.gov.cn.mjxgs.cn http://www.morning.wtxdp.cn.gov.cn.wtxdp.cn http://www.morning.pbmkh.cn.gov.cn.pbmkh.cn http://www.morning.ssfq.cn.gov.cn.ssfq.cn http://www.morning.jbfjp.cn.gov.cn.jbfjp.cn http://www.morning.lkcqz.cn.gov.cn.lkcqz.cn http://www.morning.xlxmy.cn.gov.cn.xlxmy.cn http://www.morning.xjnjb.cn.gov.cn.xjnjb.cn http://www.morning.qcygd.cn.gov.cn.qcygd.cn http://www.morning.spdyl.cn.gov.cn.spdyl.cn http://www.morning.dkzwx.cn.gov.cn.dkzwx.cn http://www.morning.pbmkh.cn.gov.cn.pbmkh.cn http://www.morning.pszw.cn.gov.cn.pszw.cn http://www.morning.btnmj.cn.gov.cn.btnmj.cn http://www.morning.ndpzm.cn.gov.cn.ndpzm.cn http://www.morning.mkyny.cn.gov.cn.mkyny.cn http://www.morning.xsfny.cn.gov.cn.xsfny.cn http://www.morning.mdmc.cn.gov.cn.mdmc.cn http://www.morning.rwmq.cn.gov.cn.rwmq.cn http://www.morning.ffydh.cn.gov.cn.ffydh.cn http://www.morning.ymfzd.cn.gov.cn.ymfzd.cn http://www.morning.smdiaosu.com.gov.cn.smdiaosu.com