我使用 JpaRepository 来保存数据,但 hibernate.show_sql 显示“选择”并且不会保存数据。以下是我的服务:
@Autowired
private UserRepository userRepository;
@PostConstruct
public void init() {
User admin = new User();
admin.setDisplayName("admin");
admin.setEmailAddress("admin@admin");
admin.setPassword("admin___");
admin.setRegisteredAt(new Date());
admin.setLastAccessAt(new Date());
admin.setUuid(UUID.randomUUID().toString());
try {
System.out.println("before save");
userRepository.save(admin);
System.out.println("after save");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
Run Code Online (Sandbox Code Playgroud)
输出如下所示:
========保存前======
休眠:从用户那里user0_ = user0_.uuid选择user0_.uuid如uuid1_0_0_,user0_.display_name如display_2_0_0_,user0_.email_address如email_ad3_0_0_,user0_.last_access_at如last_acc4_0_0_,user0_.password如password5_0_0_,user0_.registered_at如register6_0_0_?
========保存后========
以下是我的 applicationContext.xml:
<context:component-scan base-package="test">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/helloworld" />
<property name="username" value="root" />
<property name="password" value="password" />
</bean>
<bean id="myEmf"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> …Run Code Online (Sandbox Code Playgroud) 我正在使用java,我的代码中的所有异常都是从java.lang.exception派生的.将所有东西都包含在一个try-catch中是一个好主意吗?为每个困难的函数添加try-catch是个好主意吗?
因为我想让我的代码以懒惰的方式运行得更好,这意味着没有异常会导致我的程序崩溃,例如,捕获IndexOutOfBoundsException,ArrayIndexOutOfBoundsException,SQLGrammarException ......
以下是我的代码:
public MyResult function1(){
MyResult myResult = new MyResult();
try{
//all codes here
}catch(Exception e){
LOGGER.error(e);
myResult.setException(e);
}finally{
return myResult;
}
}
//more same functions using same try-catch here
public MyResult functionN(){
MyResult myResult = new MyResult();
try{
//all codes here
}catch(Exception e){
LOGGER.error(e);
myResult.setException(e);
}finally{
return myResult;
}
}
Run Code Online (Sandbox Code Playgroud) 假设您有以下两个类,第一个是Cuboid类,第二个是描述操作的类。
public class Cuboid {
private double length;
private double width;
private double height;
public Cuboid(double length, double width, double height) {
super();
this.length = length;
this.width = width;
this.height = height;
}
public double getVolume() {
return length * width * height;
}
public double getSurfaceArea() {
return 2 * (length * width + length * height + width * height);
}
}
Run Code Online (Sandbox Code Playgroud)
为什么不只使用抽象类:
public class Cuboid {
public static double getVolume(double length, double width, double height) {
return …Run Code Online (Sandbox Code Playgroud)