小编sma*_*ufo的帖子

Java 8的Optional.ifPresent和if-not-Present的功能风格?

在Java 8中,我想对一个Optional对象做一些事情,如果它存在,并做另一件事,如果它不存在.

if (opt.isPresent()) {
  System.out.println("found");
} else {
  System.out.println("Not found");
}
Run Code Online (Sandbox Code Playgroud)

但这不是一种"功能风格".

Optional有一个ifPresent()方法,但我无法链接一个orElse()方法.

因此,我不能写:

opt.ifPresent( x -> System.out.println("found " + x))
   .orElse( System.out.println("NOT FOUND"));
Run Code Online (Sandbox Code Playgroud)

在回复@assylias时,我认为不适Optional.map()用于以下情况:

opt.map( o -> {
  System.out.println("while opt is present...");
  o.setProperty(xxx);
  dao.update(o);
  return null;
}).orElseGet( () -> {
  System.out.println("create new obj");
  dao.save(new obj);
  return null;
});
Run Code Online (Sandbox Code Playgroud)

在这种情况下,当opt存在时,我更新其属性并保存到数据库.当它不可用时,我创建一个新的obj并保存到数据库.

请注意我必须返回的两个lambda null.

但是当opt存在时,两个lambdas都将被执行.obj将更新,并将新对象保存到数据库.这是因为return null在第一个lambda中.并且orElseGet()将继续执行.

java functional-programming optional java-8

239
推荐指数
7
解决办法
28万
查看次数

Spring-Data-JPA注释的setMaxResults?

我正在尝试将Spring-Data-JPA合并到我的项目中.让我困惑的一件事是如何通过注释实现setMaxResults(n)?

例如,我的代码:

public interface UserRepository extends CrudRepository<User , Long>
{
  @Query(value="From User u where u.otherObj = ?1 ")
  public User findByOhterObj(OtherObj otherObj);
}
Run Code Online (Sandbox Code Playgroud)

我只需one (and only one)要从otherObj 返回用户,但我找不到一种方法来注释maxResults ...有人可以给我一个提示吗?

(mysql抱怨:

com.mysql.jdbc.JDBC4PreparedStatement@5add5415: select user0_.id as id100_, user0_.created as created100_ from User user0_ where user0_.id=2 limit ** NOT SPECIFIED **
WARN  util.JDBCExceptionReporter - SQL Error: 0, SQLState: 07001
ERROR util.JDBCExceptionReporter - No value specified for parameter 2
Run Code Online (Sandbox Code Playgroud)

)

我找到了一个链接:https://jira.springsource.org/browse/DATAJPA-147,我试过但失败了.现在似乎不可能?为什么Spring-Data中没有内置这么重要的功能?

如果我手动实现此功能:

public class UserRepositoryImpl implements UserRepository
Run Code Online (Sandbox Code Playgroud)

我必须实现大量的预定义方法 …

java spring jpa spring-data spring-data-jpa

110
推荐指数
8
解决办法
15万
查看次数

如何获取成员变量的注释?

我想知道一个类的一些成员变量的注释,我BeanInfo beanInfo = Introspector.getBeanInfo(User.class)用来内省一个类,并使用BeanInfo.getPropertyDescriptors(),找到特定的属性,并使用Class type = propertyDescriptor.getPropertyType()来获取属性的类.

但我不知道如何将注释添加到成员变量中?

我试过了type.getAnnotations(),type.getDeclaredAnnotations()但是,两者都返回了Class的注释,而不是我想要的.例如 :

class User 
{
  @Id
  private Long id;

  @Column(name="ADDRESS_ID")
  private Address address;

  // getters , setters
}

@Entity
@Table(name = "Address")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
class Address 
{
  ...
}
Run Code Online (Sandbox Code Playgroud)

我想得到地址的注释:@Column,而不是类地址的注释(@ Entity,@ Table,@ Cache).怎么实现呢?谢谢.

java reflection annotations beaninfo

56
推荐指数
5
解决办法
12万
查看次数

如何使用JPA2的@Cacheable代替Hibernate的@Cache

通常,我使用Hibernate的@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)来缓存@Entity类,它运行良好.

在JPA2中,还有另一个@Cacheable注释,它似乎与Hibernate的@Cache具有相同的功能.为了使我的实体类独立于hibernate的包,我想尝试一下.但我不能让它发挥作用.每次简单的id查询仍然会访问数据库.

谁能告诉我哪里出错了?谢谢.

实体类:

@Entity
//@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@Cacheable(true) 
public class User implements Serializable
{
 // properties
}
Run Code Online (Sandbox Code Playgroud)

测试类:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:app.xml"})
@TransactionConfiguration(transactionManager="transactionManager")
public class UserCacheTest
{
  @Inject protected UserDao userDao;

  @Transactional
  @Test
  public void testGet1()
  {
    assertNotNull(userDao.get(2L));
  }

  @Transactional
  @Test
  public void testGet2()
  {
    assertNotNull(userDao.get(2L));
  }

  @Transactional
  @Test
  public void testGet3()
  {
    assertNotNull(userDao.get(2L));
  }
}
Run Code Online (Sandbox Code Playgroud)

测试结果显示每个"get"命中DB层(使用hibernate.show_sql = true).

Persistence.xml:

<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.use_outer_join" value="true"/>

<property name="hibernate.cache.provider_class" value="org.hibernate.cache.SingletonEhCacheProvider"/>
<property …
Run Code Online (Sandbox Code Playgroud)

orm caching hibernate jpa jpa-2.0

46
推荐指数
2
解决办法
5万
查看次数

Spring的@Scheduled错误:上下文中只能存在一个AsyncAnnotationBeanPostProcessor

我正在尝试Spring 3的@Scheduled注释.这是我的配置(app.xml):

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:aop="http://www.springframework.org/schema/aop"
  xmlns:tx="http://www.springframework.org/schema/tx"
  xmlns:task="http://www.springframework.org/schema/task"
  xsi:schemaLocation="
      http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
      http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
      http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
      http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd
      "
>

  <context:component-scan base-package="destiny.web"/>  
  <context:annotation-config/>
  // other beans

  <task:annotation-driven executor="myExecutor" scheduler="myScheduler"/>
  <task:executor  id="myExecutor"  pool-size="5"/>
  <task:scheduler id="myScheduler" pool-size="10"/>
</beans>
Run Code Online (Sandbox Code Playgroud)

这是我的服务类:

@Service
public class ServiceImpl implements Service , Serializable
{
  //other injections

  @Override
  @Transactional
  public void timeConsumingJob()
  {
    try
    {
      Thread.sleep(10*1000);
    }
    catch (InterruptedException e)
    {
      e.printStackTrace();
    }
  }

  @Override
  @Scheduled(cron="* * * * * ?") 
  public void secondly() …
Run Code Online (Sandbox Code Playgroud)

spring scheduler crontrigger spring-3

25
推荐指数
4
解决办法
3万
查看次数

如何在gRPC服务器中添加全局异常拦截器?

在gRPC中,如何添加拦截任何RuntimeException并将有意义的信息传播给客户端的全局异常拦截器?

例如,一个divide方法可能引发ArithmeticException/ by zero消息.在服务器端,我可以写:

@Override
public void divide(DivideRequest request, StreamObserver<DivideResponse> responseObserver) {
  int dom = request.getDenominator();
  int num = request.getNumerator();

  double result = num / dom;
  responseObserver.onNext(DivideResponse.newBuilder().setValue(result).build());
  responseObserver.onCompleted();
}
Run Code Online (Sandbox Code Playgroud)

如果客户端通过denominator = 0,它将得到:

Exception in thread "main" io.grpc.StatusRuntimeException: UNKNOWN
Run Code Online (Sandbox Code Playgroud)

并且服务器输出

Exception while executing runnable io.grpc.internal.ServerImpl$JumpToApplicationThreadServerStreamListener$2@62e95ade
java.lang.ArithmeticException: / by zero
Run Code Online (Sandbox Code Playgroud)

客户不知道发生了什么.

如果我想将/ by zero消息传递给客户端,我必须将服务器修改为:(如本问题所述)

  try {
    double result = num / dom;
    responseObserver.onNext(DivideResponse.newBuilder().setValue(result).build());
    responseObserver.onCompleted();
  } catch (Exception e) {
    logger.error("onError …
Run Code Online (Sandbox Code Playgroud)

java protocol-buffers grpc grpc-java

21
推荐指数
2
解决办法
8477
查看次数

ST_DWithin将参数作为度,而不是米,为什么?

ST_DWithin文件说,第三个参数(距离)以米为单位.但是当我执行一些查询时,它似乎将第3个参数作为'degree'?

这是我的简化表结构:

> \d+ theuser;
                         Table "public.theuser"
  Column  |          Type          | Modifiers | Storage  | Description 
----------+------------------------+-----------+----------+-------------
 id       | bigint                 | not null  | plain    | 
 point    | geometry               |           | main     | 
Indexes:
    "theuser_pkey" PRIMARY KEY, btree (id)
    "point_index" gist (point)
Referenced by:
    ...
Has OIDs: no
Run Code Online (Sandbox Code Playgroud)

所有点都以SRID = 4326存储.

这是查询:

> select * from theuser where ST_DWithin(point , ST_GeomFromText('POINT(120.9982 24.788)',4326) , 100 );
Run Code Online (Sandbox Code Playgroud)

它将第3个参数(100)作为'degree',因此它返回所有数据,我必须缩小到0.001以找到附近的点.

但是如何直接传递米作为第三个参数(我不想做米/度变换)?我的查询有什么问题?为什么postgreSQL不像文件那样把它作为米?

环境:

> select version();
                                                  version                                                  
-----------------------------------------------------------------------------------------------------------
 PostgreSQL 8.4.9 on i486-pc-linux-gnu, compiled …
Run Code Online (Sandbox Code Playgroud)

gis postgresql postgis srid

15
推荐指数
2
解决办法
1万
查看次数

使用Java8的可选返回的JPA的最佳实践?

我喜欢Java8的语义.我在我的DAO中使用了很多这样的代码:

  public Optional<User> findBy(String username) {
    try {
      return Optional.of(
        emp.get().createQuery("select u from User u where u.username = :username" , User.class)
        .setParameter("username" , username)
        .setMaxResults(1)
        .getSingleResult()
      );
    } catch (NoResultException e) {
      return Optional.empty();
    }
  }
Run Code Online (Sandbox Code Playgroud)

它运行良好,但这样的代码(尝试捕获NoResultException)散布在我的DAO上.我必须捕捉异常,这会以某种方式降低性能.

我想知道它是否是最好的解决方案?或任何更好的解决方案,没有try-catch?

如果不可能(因为在JPA中定义了NoResultException),任何"模板化"这样的工作流程的快捷方式?

谢谢.

java jpa java-8

15
推荐指数
1
解决办法
1万
查看次数

自动分配spring的bean名称以防止名称冲突?

在spring应用程序中,如果两个程序员开发了两个包,将@Repository注释为相同的类名,Spring将抛出"IllegalStateException":

bean类[foobar.package1.mybean]的注释指定bean名称'mybean'与同名和类[foobar.package2.mybean]的现有非兼容bean定义冲突

一种解决方案是在@Repository中添加额外的值,例如@Repository("package1.mybean")@Repository("package2.mybean"),但我正在寻找一种更有效的解决方案,可以自动缓解这种情况.我希望解决方案能够实现这些目标:

  1. 程序员可以在他的包中任意命名他们的bean className,无论名称是否与其他包(程序员)冲突.所以程序员不需要大叫'嘿,我将使用bean名称XXXXX,不要与我发生冲突'.

  2. 没有手动XML bean名称分配.

  3. 如果bean名称可以自动分配给类的完整类名,那就太棒了.

有任何想法吗 ?谢谢.(春天3)

spring

13
推荐指数
2
解决办法
6471
查看次数

如何以编程方式在线程中获取事务管理器?

我有一个wicket页面,其中包含两个Spring管理的bean,一个是DAO,另一个是Service Object:

public class MergeAccountsPage extends WebPage
{
  @SpringBean
  private MergeEmailDao mergeEmailDao;

  @SpringBean
  private MergingService mergingService;
}
Run Code Online (Sandbox Code Playgroud)

MergingService实现的方法大多是注释的@Transactional,因此涉及MergingService的每个操作都可以正常工作.

但问题出现在这里:

Link<Void> link = new Link<Void>("cancelLink") {
  @Override
  public void onClick()  {
    ma.setNewEmail(null);
    ma.setNewEmailClicked(null);
    ma.setNewEmailSentTime(null);
    mergeAccoungDao.update(ma); //not written to DB
    setResponsePage(...);
  }
};
Run Code Online (Sandbox Code Playgroud)

该链接将调用mergeAccoungDao.update(ma)以更新DB中的行.

但该数据未更新为DB,我认为这是因为DAO不裹@Transaction也不tx:adviceaop标签.

我想知道有没有办法以编程方式获取事务管理器,并手动打开/关闭事务?

注意:我可以通过在spring的XML中添加此代码来解决问题:

  <tx:advice id="txAdviceApp" transaction-manager="transactionManagerApp">
    <tx:attributes>
      <tx:method name="get*"    read-only="true"/>
      <tx:method name="save*"   propagation="REQUIRED"/>
      <tx:method name="update*" propagation="REQUIRED"/>
      <tx:method name="delete*" propagation="REQUIRED"/>
      <tx:method name="*" propagation="SUPPORTS"/>
    </tx:attributes>
  </tx:advice>

  <aop:config>
    <aop:pointcut id="methods" expression="execution(* …
Run Code Online (Sandbox Code Playgroud)

spring dao wicket jpa transactions

11
推荐指数
1
解决办法
3万
查看次数